Compare values of a grouped dataframe

Viewed 37

Hello i have the following data frame :

df=streets.groupby(['Address','Username'])['Fees'].sum()
df

Address   Username      
street1   acc1         275.39
          acc2         279.60
          acc3         249.96
street2   acc4         10634.11
          acc5         11445.39
          acc5         3832.67

I would somehow like to access the values ('Fees') and select only the groups whoose fees difference between them is less than 50 , in our exampe group with address = street1

Thank you in advance

1 Answers

IIUC, you can compute the difference between the max and min per group, if below 50, then all are within 50 of each other:

g = df.groupby(level='Address')
s = (g.max()-g.min())
idx = s[s.lt(50)].index

df.loc[idx]

output:

Address  Username
street1  acc1        275.39
         acc2        279.60
         acc3        249.96
Name: Fee, dtype: float64

NB. what you called df is in fact a Series. If it was a DataFrame you would need to do g = df.groupby(level='Address')['Fee']

Used input:

df = (pd.Series({('street1', 'acc1'): 275.39,
                 ('street1', 'acc2'): 279.6,
                 ('street1', 'acc3'): 249.96,
                 ('street2', 'acc4'): 10634.11,
                 ('street2', 'acc5'): 3832.67}, name='Fee')
        .rename_axis(['Address', 'Username'])
      )
Related