Reputation: 788
I have the following data frame
t_f m_s
uni
A False 1.2
A True 0.6
B False 0.9
B True 0.6
I am trying to get the difference of True - False for each uni and also calculate the percentage change True-False/False I am sure there is a way to do this using group by but i cant figure out how.
The output should be a data frame
m_s_diff m_s_diff_percentage
uni
A -0.6 -50%
B -0.3 -33.33%
Upvotes: 0
Views: 476
Reputation: 323226
Try this ..
df.groupby(level=0)['m_s'].diff().dropna()
uni
A -0.6
B -0.3
Name: m_s, dtype: float64
Below are solution provided by @MaxU
df.groupby(level=0)['m_s'].agg(['diff','pct_change']).dropna()
Out[502]:
diff pct_change
uni
A -0.6 -0.500000
B -0.3 -0.333333
Upvotes: 2
Reputation: 392
Use query.
df.query('t_f==True').m_s - df.query('t_f==False').m_s
Upvotes: 1