Python 需要在group by之后的列中获取排名值
我有一个数据帧,如下所示:Python 需要在group by之后的列中获取排名值,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有一个数据帧,如下所示: 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
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
说明:
我想根据每个“代码”在“Diff”中的值获得“Card_y”中的排名卡
例如
- “成衣”的“S”值的“差异”最小,为9.2,所以它排在第一位
- “服装”的值为“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]
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]
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
与groupby
和join
一起使用:
df = df.sort_values(['Card_x','Country', 'Age', 'Code', 'Diff'])
df1 = (df.groupby(['Card_x','Country', 'Age', 'Code'])['Card_y']
.apply(','.join)
.reset_index())
print (df1)
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"].apply(list).reset_index()
谢谢,但是卡片y中的值不应该在列表中。谢谢@jezrael,这个也可以。但是由于我使用了第一个代码,我不得不接受它。再次感谢。谢谢@Nathan Quinteiro,但由于我使用了第一个代码,我不得不接受它。再次感谢。