问题
I am trying to find maximum values in number of series each grouped by name of the column it was extracted from.
I have a dataframe as such:
MASTER SLAVE Value
Master_1 Slave_1 657879
Master_1 Slave_2 34343
Master_1 Slave_3 453313
Master_2 Slave_1 56667
Master_2 Slave_2 6879
Master_2 Slave_3 12333
Master_2 Slave_4 789
Master_2 Slave_5 22235
Master_3 Slave_1 65765
Master_3 Slave_2 23431
Master_3 Slave_3 445
Master_3 Slave_4 567
I need to find maximum values of first two slaves of each master.
This is so far I've gotten yet:
df.groupby('MASTER')['SLAVE'].unique()
It output series 'Slaves' values for each 'MASTER':
Master_1 [657879, 34343, 453313]
Master_2 [56667, 6879, 12333, 789, 22235]
Master_3 [65765, 23431, 445, 789, 567]
But I fail to understand what type of data I'm dealing with after this input. And how I can sort those values.
回答1:
IIUC, one option is sort_values
and GroupBy.head
with n=2:
df.sort_values('Value', ascending=False).groupby('MASTER', sort=False).head(2)
MASTER SLAVE Value
0 Master_1 Slave_1 657879
2 Master_1 Slave_3 453313
8 Master_3 Slave_1 65765
3 Master_2 Slave_1 56667
9 Master_3 Slave_2 23431
7 Master_2 Slave_5 22235
Another is using set_index
and GroupBy.nlargest
with n=2:
df.set_index('SLAVE').groupby('MASTER')['Value'].nlargest(2).reset_index()
MASTER SLAVE Value
0 Master_1 Slave_1 657879
1 Master_1 Slave_3 453313
2 Master_2 Slave_1 56667
3 Master_2 Slave_5 22235
4 Master_3 Slave_1 65765
5 Master_3 Slave_2 23431
回答2:
You can use a combination of sort and groupby:
df.sort_values(['MASTER', 'Value'], ascending=[True, False], inplace=True)
grp = df.groupby('MASTER')['SLAVE'].indices
slaves = {k: df.loc[k][:2]['SLAVE'].values for k in grp.keys()}
Will output:
{'Master_1': array(['Slave_1', 'Slave_3'], dtype=object),
'Master_2': array(['Slave_1', 'Slave_5'], dtype=object),
'Master_3': array(['Slave_1', 'Slave_2'], dtype=object)}
来源:https://stackoverflow.com/questions/56468897/return-top-n-largest-values-per-group-using-pandas