【问题标题】:How to rank within a group in Python?如何在 Python 中的组内排名?
【发布时间】:2017-10-29 08:36:29
【问题描述】:

我有以下数据框

一个>

  Bucket    C   Count
PL14    XY23081063  706
PL14    XY23326234  15
PL14    XY23081062  1
PL14    XY23143628  1
FZ595   XY23157633  353
FZ595   XY23683174  107
XM274   XY23681818  139
XM274   XY23681819  108

现在我想插入一个新列“Bucket_Rank”,它根据“Count”的降序值在每个“Bucket”下排名“C”

需要的输出: 乙>

Bucket  C   Count   Bucket_Rank
PL14    XY23081063  706 1
PL14    XY23326234  15  2
PL14    XY23081062  1   3
PL14    XY23143628  1   4
FZ595   XY23157633  353 1
FZ595   XY23683174  107 2
XM274   XY23681818  139 1
XM274   XY23681819  108 2

我尝试了以下链接中给出的解决方案

Ranking order per group in Pandas

命令:B["Bucket_Rank"] = A.groupby("Bucket")["Count"].rank("dense", ascending=False)

但它给了我以下错误..

TypeError: rank() got multiple values for argument 'axis'

During handling of the above exception, another exception occurred:

ValueError      

帮助赞赏...TIA

【问题讨论】:

  • 是的,你需要通过method='dense'。明确指定每个关键字参数。看我的回答。
  • @cᴏʟᴅsᴘᴇᴇᴅ 谢谢!

标签: python pandas dataframe rank


【解决方案1】:

使用groupby + argsort:

v = df.groupby('Bucket').Count\
         .transform(lambda x: np.argsort(-x) + 1)
v

0    1
1    2
2    3
3    4
4    1
5    2
6    1
7    2
Name: Count, dtype: int64

df['Bucket_Rank'] = v

如果您想使用rank,请指定method='dense'。最好明确指定每个关键字参数,以免混淆。

df.groupby("Bucket")["Count"]\
      .rank(method="dense", ascending=False)

0    1.0
1    2.0
2    3.0
3    3.0
4    1.0
5    2.0
6    1.0
7    2.0
Name: Count, dtype: float64

请注意,您得到的结果并不完全符合您的预期,因为相同的计数被分配了相同的排名。如果你能接受,rank 应该也可以。

【讨论】:

    猜你喜欢
    • 2015-10-29
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    相关资源
    最近更新 更多