Skip to content Skip to sidebar Skip to footer

Compute Delta Column With Pandas

I have a dataframe which looks like following: Name Variable Field A 2.3 412 A 2.9 861 A 3.5 1703 B 3.5 1731 A 4.0 2609 B 4.0 2539 A 4.6 2821 B 4.6 2779 A 5.2 30

Solution 1:

With only one 'A' value per 'Variable' group, create a Series and map the values to get the reference.

s = df[df.Name.eq('A')].set_index('Variable').Field
df['RefA'] = df.Variable.map(s)

df['Delta'] = (df.RefA - df.Field)/df.Field*100

Output: (added one line at the end of an only B group and a C group)

   Name  Variable  Field    RefA     Delta
0     A       2.3    412   412.0  0.000000
1     A       2.9    861   861.0  0.000000
2     A       3.5   1703  1703.0  0.000000
3     B       3.5   1731  1703.0 -1.617562
4     C       3.5   1761  1703.0 -3.293583
5     A       4.0   2609  2609.0  0.000000
6     B       4.0   2539  2609.0  2.756991
7     A       4.6   2821  2821.0  0.000000
8     B       4.6   2779  2821.0  1.511335
9     A       5.2   3048  3048.0  0.000000
10    B       5.2   2979  3048.0  2.316213
11    A       5.8   3368  3368.0  0.000000
12    B       5.8   3216  3368.0  4.726368
13    B       6.5   1231     NaN       NaN

Post a Comment for "Compute Delta Column With Pandas"