简体   繁体   中英

Pandas find cell based on month of datetime multiindex

The result of:

groups = merge.groupby([pd.Grouper(key='dt', freq='M'), 'rate']).sum()

Is:

                 consumption
dt         rate             
2017-11-30 flat  203688000.0
2017-12-31 flat  217094000.0
2018-01-31 flat  265193000.0
2018-02-28 flat  184570000.0
2018-03-31 flat  160481000.0
2018-04-30 flat  178990000.0
2018-05-31 flat  167311000.0
2018-06-30 flat  178714000.0
2018-07-31 flat  262210000.0
2018-08-31 flat  198391000.0
2018-09-30 flat  189134000.0
2018-10-31 flat  186050000.0

Now I can access consumption for a particular dt/rate like so:

groups.loc[(date, rate)]['consumption']

But I'm having trouble writing my loc so that I can find a column based on the month and the rate.

I've tried using:

groups.loc[groups['dt'].month == month.month & groups['rate'] == k]['consumption']

But I get KeyError because dt and rate are indices.

Is there a way to do this? Or perhaps modify the groupby so it gives me a month index instead?

IIUC. get_level_values

df.loc[(df.index.get_level_values(0).month == 11) & (df.index.get_level_values(1) == 'flat')]['consumption']
Out[1814]: 
dt          rate
2017-11-30  flat    203688000.0
Name: consumption, dtype: float64

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