Dmi*_*nov 3 pandas pandas-groupby
import pandas as pd
d = {
'resource': [1,2,3,4,5,6,7],
'branch': ['a', 'b', 'c', 'a', 'a', 'c', 'b'],
'utilization': [0.7, 0.76, 0.9, 0.3, 0.55, 0.87, 0.71]
}
df = pd.DataFrame(data=d)
Run Code Online (Sandbox Code Playgroud)
像这样的东西:
df.groupby('branch')[['resource', 'utilization']].nlargest(2, 'utilization')
Run Code Online (Sandbox Code Playgroud)
我尝试了以下方法:
f = lambda x: x.sort_values('utilization', ascending=False)
df.groupby('branch', sort=False).apply(f).nlargest(3, 'utilization')
Run Code Online (Sandbox Code Playgroud)
但是当我在每组中需要前N时,它会让我在所有记录中排名前三
resource branch utilization
branch
c 2 3 c 0.90
5 6 c 0.87
b 1 2 b 0.76
Run Code Online (Sandbox Code Playgroud)
可以用sort_values+tail
df.sort_values('utilization').groupby('branch').tail(2)
branch resource utilization
4 a 5 0.55
0 a 1 0.70
6 b 7 0.71
1 b 2 0.76
5 c 6 0.87
2 c 3 0.90
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42 次 |
| 最近记录: |