SHARE
TWEET

pandas - groupby - substrack from first

furas Jul 9th, 2018 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top