Pandas根据日期时间多指数查找单元格

时间:2018-04-09 16:15:37

标签: python pandas

结果:

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,因为dtrate是索引。

有办法做到这一点吗?或者修改groupby以便它给我一个月索引?

1 个答案:

答案 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