如何基于其他列在Python中创建等级列

时间:2019-01-07 19:13:01

标签: python python-3.x pandas

我有一个如下所示的python数据框:

enter image description here

此数据框已按'transaction_count'降序排列。我想在该数据帧中创建另一个列“ rank”,其中包含cust_ID的出现次数。我的愿望输出如下所示:

enter image description here

对于transaction_count = 4的cust_ID = 1234,等级将为1,对于下一次出现的cust_ID = 1234,等级将为2,依此类推。

除了其他方面,我还尝试了以下方法:

df['rank'] = df["cust_ID"].value_counts()
df.head(10)

但是排名列被创建为所有NaN值 enter image description here

任何有关如何解决此问题的建议将不胜感激!

2 个答案:

答案 0 :(得分:2)

使用groupby + cumcount

df['rank'] = df.groupby('cust_ID').cumcount() + 1
print(df['rank'])

输出

0    1
1    2
2    1
3    1
4    2
5    3
Name: rank, dtype: int64

答案 1 :(得分:2)

您可以这样做:

df['rank'] = df.groupby('cust_ID')['transaction_count'].rank(ascending=False)

输出:

    cust_ID     associate_ID    transaction_count   rank
0   1234           608          4                   1.0
1   1234           785          1                   2.0
2   4789           345          2                   1.0
3   3456           268          5                   1.0
4   3456           725          3                   2.0
5   3456           795          1                   3.0

请注意,这不仅基于transaction_count值给出了交易次数,而且还给出了交易等级。

相关问题