如何使用Python和Pandas创建十分位数和五分位数列,根据大小对另一个变量进行排名?

23

我有一个数据框,其中包含一个列Investment,表示交易员投资的金额。我想在数据框中创建两个新列;一个给出基于Investment大小的十分位数排名,另一个给出五分位数排名。我希望1代表投资最大的十分位数,10代表最小的十分位数;同样,我希望1代表投资最大的五分位数,5代表最小的五分位数。

作为Pandas的新手,有没有办法可以轻松地做到这一点?谢谢!

1个回答

43

你要寻找的功能在 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

谢谢@Dan,后者正是我在寻找的,它运行得很好!我会更多地了解qcut工具,它真的很方便!再次感谢 :) - finstats

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接