我在Pandas中有一个表达式,其中我按国家对前三个值进行排序:
Country | Value
---------------------|------
Germany | 102.1
Germany | 90.3
Germany | 44.6
Switzerland | 59.9
Switzerland | 35.3
Switzerland | 21.6
...and so on
这是我使用CCD_ 1获得的。现在,我想添加第三列,将国家内的排名与值关联起来:
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'
,因为在转换为integers
:的情况下,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