这是我从 groupby 获得的 multiIndex 数据框,其中我有 2 个索引 ['YearMonth', 'product_id'] 和列名 ['count'] 我已经尝试过文档和其他 stackoverflow 建议中的示例,但仍然无法索引product_id == 6818 for每个 YearMonth 索引列。
df = df.groupby(['YearMonth','product_id'])[['count']].sum()
df.head(5)
Out[54]:
count
YearMonth product_id
2017-05-01 6818 3
7394 1 7394 1
8369 1 8369 1
8504 1 8504 1
8666 1 8666 1
In [55]:
df.columns
Out[55]:
Index(['count'], dtype='object')
In [56]:
df.index.names
Out[56]:
FrozenList(['YearMonth', 'product_id'])
In [59]:
df.loc[('2017-05-01',0),'count']
我试过:简单的索引,df['YearMonth']
但它只适用于列而不是索引
df.loc\ix\iloc在这个stackoverflow question中给出
df.loc[('2017-05-01',0)]
我总是得到 KeyError,例如KeyError: ('2017-05-01', 0)
,KeyError: 'YearMonth'
以及我尝试unstack方法df.unstack(level=0)
并进行了与上述相同的操作
有人可以解释我错过了什么吗?提前致谢
您的示例 DF 看起来不“健康” - 我已经修复了它,现在看起来如下所示:
In [121]: df
Out[121]:
count
YearMonth product_id
2017-05-01 6818 3
7394 1
8369 1
8504 1
8666 1
选项1:
In [122]: df.loc[pd.IndexSlice[:, 6818], :]
Out[122]:
count
YearMonth product_id
2017-05-01 6818 3
选项 2:适用于命名索引
In [145]: df.query("product_id in [6818]")
Out[145]:
count
YearMonth product_id
2017-05-01 6818 3
选项 3:
In [146]: df.loc[(slice(None), 6818), :]
Out[146]:
count
YearMonth product_id
2017-05-01 6818 3
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句