我有一个 pandas 数据框,其中包含一个名为“promo_type”的字段,我使用 astype 将其转换为分类:
df['promo_type'] = df['promo_type'].astype('category')
稍后在代码中我想在字段中添加另一个类别,如下所示:
df['promo_type'].add_categories('0')
我得到这个错误:
AttributeError: 'Series' object has no attribute 'add_categories'
我已经检查过我的 pandas 版本确实有 add_categories,并且 add_categories 是 df['promo_type'] 的可用方法。
我不知道为什么这不起作用。
提前感谢您的帮助。
您错过了
cat
访问器。你必须使用Series.cat.add_categories
:
df['promo_type'] = df['promo_type'].cat.add_categories('0')
设置:
df = pd.DataFrame({'promo_type': ['a', 'b', 'c']}).astype('category')
print(df['promo_type'])
# Output
0 a
1 b
2 c
Name: promo_type, dtype: category
Categories (3, object): ['a', 'b', 'c']
添加类别:
df['promo_type'] = df['promo_type'].cat.add_categories('0')
print(df['promo_type'])
# Output
0 a
1 b
2 c
Name: promo_type, dtype: category
Categories (4, object): ['a', 'b', 'c', '0'] # <- HERE
更新
只有在使用
add_categories
时,才可以在没有 cat
访问器的情况下使用 CategoricalIndex
:
df = pd.DataFrame({'promo_type': ['a', 'b', 'c']})
catx = pd.CategoricalIndex(df['promo_type'])
print(catx)
# Output
CategoricalIndex(['a', 'b', 'c'], categories=['a', 'b', 'c'], ordered=False, dtype='category', name='promo_type')
修改类别:
catx = catx.add_categories('0')
print(catx)
# Output
CategoricalIndex(['a', 'b', 'c'], categories=['a', 'b', 'c', '0'], ordered=False, dtype='category', name='promo_type')