如何使用Python和Pandas创建分位数和五分位数列以排名另一个变量?
我有一个数据表,其中有一列叫做 Investment
,表示交易者投资的金额。我想在这个数据表中创建两个新列;一个是根据 Investment
的大小来给出十分位排名,另一个是给出五分位排名。我希望1代表投资最多的十分位,10代表投资最少的十分位。同样,我希望1代表投资最多的五分位,5代表投资最少的五分位。
我刚开始学习Pandas,不知道有没有简单的方法可以做到这一点?谢谢!
1 个回答
45
你想要的功能可以在 pandas.qcut
中找到,具体可以查看这个链接:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.qcut.html
In [51]: import numpy as np
In [52]: import pandas as pd
In [53]: investment_df = pd.DataFrame(np.arange(10), columns=['investment'])
In [54]: investment_df['decile'] = pd.qcut(investment_df['investment'], 10, labels=False)
In [55]: investment_df['quintile'] = pd.qcut(investment_df['investment'], 5, labels=False)
In [56]: investment_df
Out[56]:
investment decile quintile
0 0 0 0
1 1 1 0
2 2 2 1
3 3 3 1
4 4 4 2
5 5 5 2
6 6 6 3
7 7 7 3
8 8 8 4
9 9 9 4
通常情况下,用最小的数字来标记最大的百分位数并不是标准做法,但你可以通过以下方式实现这个功能:
In [60]: investment_df['quintile'] = pd.qcut(investment_df['investment'], 5, labels=np.arange(5, 0, -1))
In [61]: investment_df['decile'] = pd.qcut(investment_df['investment'], 10, labels=np.arange(10, 0, -1))
In [62]: investment_df
Out[62]:
investment decile quintile
0 0 10 5
1 1 9 5
2 2 8 4
3 3 7 4
4 4 6 3
5 5 5 3
6 6 4 2
7 7 3 2
8 8 2 1
9 9 1 1