【发布时间】:2018-03-17 21:43:04
【问题描述】:
使用 pandas IndexSlice,是否可以使用整数列表?当我使用整数列表时出现 KeyError: 'the label [xxxx] is not in the [columns]'(即使 multiIndex 级别中的值被格式化为字符串):
vals = np.random.randn(4)
df = pd.DataFrame({'l1': ['A', 'B', 'C', 'B'], 'l2': ['9876', '6789', '5432',
'1234'], 'l3': ['Y', 'X', 'Y', 'Y'], 'value': vals})
df.set_index(['l1', 'l2', 'l3'], inplace=True)
idx = pd.IndexSlice
# None of the following works
df.loc[idx[:, 6789, :]]
df.loc[idx[:, [6789, 1234], :]]
df.reset_index(inplace=True)
df.l2 = df.l2.astype('str')
df.set_index(['l1', 'l2', 'l3'], inplace=True)
df.loc[idx[:, '6789', :]]
【问题讨论】:
标签: python pandas dataframe indexing