python - 将序号添加到 Pandas 中的 groupby().head(n) 表达式中

标签 python pandas pandas-groupby

我在 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.rankmethod='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/

相关文章:

python - 似乎无法从字符串中删除数字

python - 数据框的原始值没有变化

Python Pandas 使用日期时间数据按日期分组

Python PIL 在渲染文本时添加额外的字符

python - 无法导入名称getoutput

python - 如何总结不同的groupby组合?

python - 使用 python 和 pandas 按季节分组数据

python - 带有 bool OR 的 Pandas groupby

python - Mercurial 由于 qct 扩展而崩溃 - 我尚未启用该扩展

python - 从 Django/Python 上传特定文件