拥有一个小玩具数据框:
df = pd.DataFrame({
'clients': pd.Series(['A', 'A', 'A', 'B', 'B']),
'Price': pd.Series([1.0, 22.0, 15.0, 7.5, 5.0])
})
我想根据每个客户的价格顺序创建一个新标签:
Price clients new_col
0 1.0 A 1
1 22.0 A 2
2 15.0 A 3
3 7.5 B 2
4 5.0 B 1
希望这个例子澄清一下。
我显然可以对dataframe
进行排序,但我不确定如何翻译标签。行索引不受sort_index
:
Price clients
0 1.0 A
2 15.0 A
1 22.0 A
4 5.0 B
3 7.5 B
答案 0 :(得分:2)
在“客户”列上执行groupby
,然后在传递transform
方法的“价格”列上致电rank
:
In [409]:
df = pd.DataFrame({
'clients': pd.Series(['A', 'A', 'A', 'B', 'B']),
'Price': pd.Series([1.0, 22.0, 15.0, 7.5, 5.0])
})
df['rank'] = df.groupby('clients')['Price'].transform(pd.Series.rank)
df
Out[409]:
Price clients rank
0 1.0 A 1
1 22.0 A 3
2 15.0 A 2
3 7.5 B 2
4 5.0 B 1
transform
将返回与原始df