3

我有一个类别列,我想用一个系列来填充。我试过这个:

df = pd.DataFrame({'key': ['a', 'b'], 'value': ['c', np.nan]})
df['value'] = df['value'].astype("category")
df['value'] = df['value'].cat.add_categories(df['key'].unique())
print(df['value'].cat.categories)
df['value'] = df['value'].fillna(df['key'])
print(df)

预期输出:

Index(['c', 'a', 'b'], dtype='object')
  key value
0   a     c
1   b     b

实际输出:

Index(['c', 'a', 'b'], dtype='object')
  key value
0   a     a
1   b     b
4

2 回答 2

3

这似乎是一个错误,但幸运的是,解决方法非常简单。填充时,您必须将“值”视为字符串列。

df['value'] = pd.Categorical(
    df.value.astype(object).fillna(df.key), categories=df.stack().unique())
df

  key value
0   a     c
1   b     b
于 2019-02-18T20:50:38.707 回答
2

文档中,分类数据将接受标量而不是系列,因此您可能需要将其转换回系列

df.value.astype('object').fillna(df.key) # then convert to category again
Out[248]: 
0    c
1    b
Name: value, dtype: object

value : 用于填充孔的标量值(例如 0)

于 2019-02-18T20:55:39.607 回答