.loc for Pandas中的CategoricalIndex

时间:2017-09-04 14:40:40

标签: python pandas

我尝试使用.loc访问基于CategoricalIndex的Pandas数据帧的行,但我得到TypeError。最低工作示例为

import pandas as pd

df = pd.DataFrame({'foo': rand(3), 'future_index': [22, 13, 87]})
df['future_index'] = df['future_index'].astype('category')
df = df.set_index('future_index')

然后,尝试访问与标签13对应的行

df.loc[13]

我得到了

TypeError: cannot do label indexing on <class 'pandas.core.indexes.category.CategoricalIndex'> with these indexers [13] of <class 'int'>

尽管

13 in df.index

True。我知道我最终可以用

获得13的索引
df.index.get_loc(13)

但是,为什么上述更简单的方法不起作用?我错过了什么?

干杯。

1 个答案:

答案 0 :(得分:2)

对我来说工作:

print (df.loc[pd.CategoricalIndex([13])])
              foo
future_index     
13              2

但如果按照EdChum转换为str,则效果很好:

df = pd.DataFrame({'foo': [1,2,3], 'future_index': [22, 13, 87]})
df['future_index'] = df['future_index'].astype(str).astype('category')
df = df.set_index('future_index')
print (df)

print (df.loc['13'])
foo    2
Name: 13, dtype: int64