我尝试使用.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
。我知道我最终可以用
df.index.get_loc(13)
但是,为什么上述更简单的方法不起作用?我错过了什么?
干杯。
答案 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