我有一个数据框,其中包含一个列Investment
,表示交易员投资的金额。我想在数据框中创建两个新列;一个给出基于Investment
大小的十分位数排名,另一个给出五分位数排名。我希望1代表投资最大的十分位数,10代表最小的十分位数;同样,我希望1代表投资最大的五分位数,5代表最小的五分位数。
作为Pandas的新手,有没有办法可以轻松地做到这一点?谢谢!
你要寻找的功能在 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