结果:
groups = merge.groupby([pd.Grouper(key='dt', freq='M'), 'rate']).sum()
时:
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
现在我可以像这样访问特定dt / rate的消费:
groups.loc[(date, rate)]['consumption']
但我在编写loc
时遇到问题,以便根据月和费率找到一列。
我尝试过使用:
groups.loc[groups['dt'].month == month.month & groups['rate'] == k]['consumption']
但我得到KeyError
,因为dt
和rate
是索引。
有办法做到这一点吗?或者修改groupby
以便它给我一个月索引?
答案 0 :(得分:1)
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