简体   繁体   中英

Group pandas multiindex dataframe by all the indices

My dataframe looks like

Out[229]: 
                          Value
id            date             
1             1945-11-01    148
              1945-11-02    150
              1945-11-06    132
              1945-11-07    132
              1945-12-06    166
              1945-12-07    179
              1945-12-08    182
              1945-12-09    174
              1945-12-10    159

I'm trying something like

by_month = df.groupby(['id', lambda x: x.month])

in order to group my dataset first by id and then by month for further processing and obtain the following:

                          Value
id            date             
1             11            148
1             11            150
1             11            132
1             11            132
1             12            166
1             12            179
1             12            182
1             12            174
1             12            159

I have no clue why I'm getting

KeyError: u'no item named id'

although df.index.names output FrozenList([u'id', u'date']) .

Any hints?

That is not the right of accessing MultiIndex , this should be right:

df.groupby(by=[df.index.get_level_values(0), 
           pd.to_datetime(df.index.get_level_values(1)).month]) 
#omit pd.to_datetime if already done so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM