我在 Pandas 中有一个表达式,可以按国家/地区对前三个值进行排序:
Country | Value
---------------------|------
Germany | 102.1
Germany | 90.3
Germany | 44.6
Switzerland | 59.9
Switzerland | 35.3
Switzerland | 21.6
...and so on
我使用df.groupby("Country").head(3)[["Country", "Value"]]
获得。现在,我想附加第三列,将国家/地区内的排名与值关联起来:
Country | Value | Rank
---------------------|--------|------
Germany | 102.1 | 1
Germany | 90.3 | 2
Germany | 44.6 | 3
Switzerland | 59.9 | 1
Switzerland | 35.3 | 2
Switzerland | 21.6 | 3
...and so on
我怎样做才能最好地做到这一点?
最佳答案
我相信你需要GroupBy.rank
和 method='dense'
的排名始终按 Value
列的排序值在组之间增加 1,并转换为 整数
:
df['Rank'] = df.groupby("Country")["Value"].rank(method='dense', ascending=False).astype(int)
print (df)
Country Value Rank
0 Germany 102.1 1
1 Germany 90.3 2
2 Germany 44.6 3
3 Switzerland 59.9 1
4 Switzerland 35.3 2
5 Switzerland 21.6 3
如果需要计数器那么最好使用GroupBy.cumcount
:
df['Rank1'] = df.groupby("Country").cumcount() + 1
在更改的数据中最能看出差异:
print (df)
Country Value
0 Germany 90.3 second largest per group - 2
1 Germany 102.1 largest per group - 1
2 Germany 44.6 third largest per group - 3
3 Switzerland 21.6
4 Switzerland 35.3
5 Switzerland 59.9
df['Rank'] = df.groupby("Country")["Value"].rank(method='dense', ascending=False).astype(int)
df['Rank1'] = df.groupby("Country").cumcount() + 1
print (df)
Country Value Rank Rank1
0 Germany 90.3 2 1
1 Germany 102.1 1 2
2 Germany 44.6 3 3
3 Switzerland 21.6 3 1
4 Switzerland 35.3 2 2
5 Switzerland 59.9 1 3
关于python - 将序号添加到 Pandas 中的 groupby().head(n) 表达式中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58579452/