Advertisement
furas

pandas - groupby - substrack from first

Jul 9th, 2018
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.46 KB | None | 0 0
  1. import pandas as pd
  2.  
  3. df = pd.DataFrame({
  4.     'b': ['s', 'j', 'm', 's', 'j'],
  5.     'c': [12, 16, 5, 7, 8],
  6. })
  7. #print(df)
  8.  
  9. df['d'] = pd.np.zeros(df.shape[0])
  10. #print(df)
  11.  
  12. for key, grp in df.groupby('b'):
  13.     #print('---')
  14.     #print(key)
  15.     #print(grp)
  16.     # it calculates first - sum(rest)
  17.     result = grp['c'].iloc[0] - grp['c'].iloc[1:].sum()
  18.     first_index = grp.index[0]
  19.     df['d'][first_index] = result
  20.     #print(key, result)
  21.  
  22. print(df)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement