2014-10-21 51 views
5

我有一個數據框,其中包含一個包含Investment的列,它表示交易者投資的金額。我想在數據框中創建2個新列;一個給出十分位等級,另一個給予基於Investment大小的五分位等級。我希望1代表最大投資的10分,10代表最小投資。同樣,我希望1代表具有最大投資的五分位數,5代表最小的五分位數。如何使用Python,Pandas創建Decile和Quintile列以基於大小對另一個變量進行排序?

我是熊貓新手,那麼有沒有一種方法可以輕鬆做到這一點? 謝謝!

回答

8

你要找的功能是在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 
+0

感謝@丹後者做到這一點是我正在尋找,它運作良好!我會在qcut上閱讀更多內容,它非常方便! 再次感謝:) – roland 2014-10-23 00:58:06

相關問題