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

2024-04-29 11:59:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我对熊猫还不熟悉,有没有办法让我轻松地做到这一点呢? 谢谢!


Tags: 数据交易者代表金额办法小数点investment
1条回答
网友
1楼 · 发布于 2024-04-29 11:59:40

您要查找的功能位于pandas.qcuthttp://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

相关问题 更多 >