2017-10-08 110 views
1

我有以下數據框:如何引用熊貓數據框的索引字段?

payment_method_id payment_plan_days plan_list_price actual_amount_paid date 
msno         
YyO+tlZtAXYXoZhNr3Vg3+dfVQvrBVGO8j1mfqe4ZHc= 41 30 129 129 2015-01-01 
AZtu6Wl0gPojrEQYB8Q3vBSmE2wnZ3hi1FbK1rQQ0A4= 41 30 149 149 2015-01-01 
UkDFI97Qb6+s2LWcijVVv4rMAsORbVDT2wNXF0aVbns= 41 30 129 129 2015-01-02 

的關鍵是「msno」,我需要找出是否多數「msno」僅使用在不同的日期一個payment_method_id。

於是,我就按 「msno」, 「payment_method_id」,使用

transactions.groupby(['msno', 'payment_method_id']).count() 

,但得到的錯誤:KeyError異常: 'msno'

組利用等領域做工精細,如:

transactions.groupby(['payment_plan_days', 'payment_method_id']).count() 

那麼對於msno,我可以即使使用groupby level=0

transactions.groupby(level=0) 

但我不能將包含第一列的兩個級別分組。

這是它看起來在transactions.columns

Index(['payment_method_id', 'payment_plan_days', 'plan_list_price', 'actual_amount_paid', 'date'] dtype='object')

什麼建議嗎?

回答

1

我認爲你需要reset_index的轉換索引列,因爲你的熊貓版本是波紋管0.20.1

Strings passed to DataFrame.groupby() as the by parameter may now reference either column names or index level names. Previously, only column names could be referenced. This allows to easily group by a column and index level at the same time.

transactions.reset_index().groupby(['msno', 'payment_method_id']).count() 

所以升級後,你的代碼應該很好地工作:

transactions.groupby(['msno', 'payment_method_id']).count() 

公告:

之間的區別和sizecount省略NaN s和size沒有。