【发布时间】:2019-06-24 09:38:01
【问题描述】:
我一直在研究 Pandas Dataframe,但在检索更高级别索引的 sub_level 索引时遇到问题。
这张图片显示了我的数据框结构:
例如,在上图中,我想检索只存在于“设备+标签”键“-444/0”的“DCSID”索引,即“-111111”、“-222222”和“-333333”。
自从 df.loc[ '-444/0'] 返回键 '-444/0' 的子数据框,并使用 index.levels[0] 检索我以后想要的结果。
这是执行df.loc['-444/0']的结果:
它不起作用,这不符合逻辑,因为我认为 df.loc['-444/0']返回一个新的数据框。
无论如何,我发现 df.index.levels[1] 等价于 df.iloc['-444/0' ].index.levels[0] 都返回“DCSID”中所有索引的列表:
Int64Index([-444444, -333333, -305500, -304445, -301064, -300015, -299069, -297188, -296241, -295295, ... -17132、-15622、-14112、-12602、-9596、-8086、-6576、 -5066,-2060,-542], dtype='int64', name='DCSID', length=120)
这是我的代码的一部分:
for i in df.index.levels[0]: #Choose from first level
for j in df.loc[i].index.levels[0]: #Choose from second level going through the i-th first level
for k in df.loc[i, j, slice(None)].index: #Choose from third level going through the j-th second level
#Code here
【问题讨论】:
-
请提供样本数据
标签: python pandas dataframe jupyter-notebook jupyter