2017-10-08 2 views
1

Ich habe folgenden Datenrahmen:Wie verweist man auf das Indexfeld des Pandas-Datenrahmens?

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 

Der Schlüssel ist „msno“, ich brauche, um herauszufinden, ob Mehrheit des „msno“ ist nur ein payment_method_id in verschiedenem Datum.

Also versuchte ich zu einer Gruppe von "msno", "payment_method_id", mit

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

aber bekam Fehler: KeyError: 'msno'

Gruppe unter Verwendung von anderen Bereichen funktionieren, zB:

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

Dann für die msno, kann ich mit noch groupby level=0

transactions.groupby(level=0) 

Aber ich kann zwei Ebenen nicht gruppieren, die die erste Spalte enthält.

Dies ist, was es sieht in transactions.columns

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

Jeder Vorschlag?

Antwort

1

Ich glaube, Sie reset_index für convert Index Spalte müssen, weil Ihre Pandas Version unten ist 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() 

So nach dem Code-Upgrade sollte funktionieren:

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

Hinweis :

Unterschied zwischen count und size ist count unterlassen NaN s und size nicht.

Verwandte Themen