gpt4 book ai didi

python - 需要在分组后获得列中的排名值

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:06 24 4
gpt4 key购买 nike

我有一个数据框如下:

Card_x  Country Age Code    Card_y  Diff
S INDIA Adult Garments S 9.2
S INDIA Adult Grocery S 21.33
S INDIA Adult Garments M 151.4
S INDIA Adult Grocery M 202.15
S INDIA Adult Grocery G 48.7
S INDIA Adult Garments G 126.82
S INDIA Adult Garments E 19.17
S INDIA Adult Grocery E 276.09
S INDIA Adult Grocery D 3.05
S INDIA Adult Garments D 69.43
S INDIA Adult Grocery A 109.47
S INDIA Adult Garments A 161.75

我期望的数据框:

Card_x  Country Age     Code       Card_y
S INDIA Adult Garments S,E,D,G,M,A
S INDIA Adult Grocery D,S,G,A,M,E

解释:我想根据每个“代码”的“差异”中的值获得“Card_y”中的排名卡

例如。

  • 'Garments' 的值 'S' 具有最少的“Diff” - 9.2,所以它排在第一位。
  • 'Garments' 的值为 'E' 和“Diff” - 19.17,所以它排在第二位,依此类推。

我试过下面的代码:

def get_cards(x):
extra = {'S', 'A','M', 'E', 'G','D'}.difference(set(x))
x=x.append(pd.Series(list(extra)))
return ",".join(x.tolist())

temp1.groupby(['Card_x','Country', 'Age', 'Code'])['Card_y'].apply(lambda x: get_cards(x) ).reset_index()

但我没有得到预期的结果。

最佳答案

尝试:

df.sort_values('Diff').groupby(['Card_x','Country','Age','Code'])['Card_y']\
.agg(list).reset_index()

输出:

  Card_x Country    Age      Code              Card_y
0 S INDIA Adult Garments [S, E, D, G, M, A]
1 S INDIA Adult Grocery [D, S, G, A, M, E]

不在列表中然后使用

df.sort_values('Diff').groupby(['Card_x','Country','Age','Code'])['Card_y']\
.agg(','.join).reset_index()

输出:

   Card_x Country    Age      Code       Card_y
0 S INDIA Adult Garments S,E,D,G,M,A
1 S INDIA Adult Grocery D,S,G,A,M,E

关于python - 需要在分组后获得列中的排名值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54093274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com