在 Pandas DataFrameGroupBy 对象上使用 `rank`

use*_*685 2 python pandas

我在由三列 [id, country, volume] 组成的数据框中有一些简单的数据,其中索引是“id”。

我可以执行简单的操作,例如:

df_vol.groupby('country').sum()
Run Code Online (Sandbox Code Playgroud)

它按预期工作。当我尝试使用 rank() 时,它没有按预期工作,结果是一个空的数据框。

df_vol.groupby('country').rank()
Run Code Online (Sandbox Code Playgroud)

结果不一致,在某些情况下它有效。以下也按预期工作:

df_vol.rank()
Run Code Online (Sandbox Code Playgroud)

我想返回类似的东西:

vols = []
for _, df in f_vol.groupby('country'):
    vols.append(df['volume'].rank())
pd.concat(vols)
Run Code Online (Sandbox Code Playgroud)

任何想法为什么非常感谢!

jez*_*ael 5

您可以添加 column by []- 仅对 column 调用函数Volume

df_vol.groupby('country')['volume'].rank()
Run Code Online (Sandbox Code Playgroud)

样本:

df_vol = pd.DataFrame({'country':['en','us','us','en','en'],
                   'volume':[10,10,30,20,50],
                   'id':[1,1,1,2,2]})
print(df_vol)
  country  id  volume
0      en   1      10
1      us   1      10
2      us   1      30
3      en   2      20
4      en   2      50

df_vol['r'] = df_vol.groupby('country')['volume'].rank()
print (df_vol)
  country  id  volume    r
0      en   1      10  1.0
1      us   1      10  1.0
2      us   1      30  2.0
3      en   2      20  2.0
4      en   2      50  3.0
Run Code Online (Sandbox Code Playgroud)