2016-01-28 64 views
3

我有索引的month列數據框(使用df = df.set_index('month')集,如果這是相關的):熊貓:按指數值分組,然後計算分位數?

   org_code ratio_cost 
month 
2010-08-01 1847  8.685939  
2010-08-01 1848  7.883951  
2010-08-01 1849  6.798465  
2010-08-01 1850  7.352603  
2010-09-01 1847  8.778501  

我想添加一個新列名爲quantile,這將指定位數的值的每一行,根據其月份的價值爲ratio_cost

所以上面的例子可能是這樣的:

   org_code ratio_cost quantile 
month 
2010-08-01 1847  8.685939  100 
2010-08-01 1848  7.883951  66.6 
2010-08-01 1849  6.798465  0 
2010-08-01 1850  7.352603  33.3 
2010-09-01 1847  8.778501  100 

我怎樣才能做到這一點?我試過這個:

df['quantile'] = df.groupby('month')['ratio_cost'].rank(pct=True) 

但是我得到了KeyError: 'month'

UPDATE:我可以重現該錯誤。

這裏是我的CSV文件:http://pastebin.com/raw/6xbjvEL0

這裏是重現該錯誤代碼:

df = pd.read_csv('temp.csv') 
df.month = pd.to_datetime(df.month, unit='s') 
df = df.set_index('month') 
df['percentile'] = df.groupby(df.index)['ratio_cost'].rank(pct=True) 
print df['percentile'] 

我用熊貓0.17.1在OSX。

+0

嘗試'DF [ '分位數'] = df.groupby(df.index)[ 'ratio_cost']秩(PCT = TRUE)'或'DF。 ['quantile'] = df.groupby(level = 0)['ratio_cost']。rank(pct = True)' – jezrael

+0

謝謝。我試過'print df.groupby(level = 0)',但它給了我'提升ValueError'。與'df.groupby(df.index)'相同。 – Richard

+0

啊,月份列是日期時間 - 是一個問題嗎?我已經更新了問題以顯示它的產生。 – Richard

回答

6

你必須sort_indexrank前:

import pandas as pd 

df = pd.read_csv('http://pastebin.com/raw/6xbjvEL0') 

df.month = pd.to_datetime(df.month, unit='s') 
df = df.set_index('month') 

df = df.sort_index() 

df['percentile'] = df.groupby(df.index)['ratio_cost'].rank(pct=True) 
print df['percentile'].head() 

month 
2010-08-01 0.2500 
2010-08-01 0.6875 
2010-08-01 0.6250 
2010-08-01 0.9375 
2010-08-01 0.7500 
Name: percentile, dtype: float64 
+0

謝謝,你的例子適用於我,甚至設置'df = df.set_index('month')',然後切換到'df.groupby(df.index)...'。我將用它來調試。 – Richard

+0

也許你可以分享你的數據,如果沒有信心...因爲它對我很好。 – jezrael

+0

什麼是你的熊貓版本'print pd.show_versions()'? – jezrael