【问题标题】:pandas fillna Currently only can fill with dict/Series column by columnpandas fillna 目前只能用 dict/Series 逐列填充
【发布时间】:2018-01-30 14:27:10
【问题描述】:

我有以下df

A
1.0
2.0
3.0
NaN

我尝试用fillnaNaN 替换为字符串not existed

df.fillna(value={'A': 'not existed'}, axis=1, inplace=True)

但我收到以下错误,

NotImplementedError: Currently only can fill with dict/Series column by column

如果我使用replace,它将起作用,

df['A'].replace(np.nan, 'not existed')

我想知道为什么会这样。

【问题讨论】:

  • 如果你喜欢它,有一个简单的方法:df['A'] = df['A'].fillna('not existed')

标签: python python-3.x pandas dataframe


【解决方案1】:

对我来说,删除 axis=1:

print (df)
     A    B
0  NaN  NaN
1  2.0  7.0
2  3.0  8.0
3  NaN  7.0

df.fillna({'A': 'not existed'}, inplace=True)
print (df)
             A    B
0  not existed  NaN
1            2  7.0
2            3  8.0
3  not existed  7.0

df.fillna({'A': 'not existed', 'B':'nwwww'}, inplace=True)
print (df)
             A      B
0  not existed  nwwww
1            2      7
2            3      8
3  not existed      7

【讨论】:

  • 是的,你是仪式。如果有 2 列我要删除 NaNdf[['A', 'B']].fillna(value={'A': 'not exist', 'B': 'not exist'}, inplace=True)NaN 无法替换为字符串
  • 不要使用subset - df[['A', 'B']],那么它工作得很好。检查编辑的答案。
【解决方案2】:

当您在 DataFrame 上使用 fillna 时,您应该传递一个字典,其中包含要填充的每一列的值,如 here 所述。

无论如何,您的错误与您使用axis 的方式有关,请查看此工作示例:

import pandas

x = pandas.DataFrame({
    'x_1': [0, 1, 2, 3, 0, 1, 2, None, ],},
    index=[0, 1, 2, 3, 4, 5, 6, 7])

x.fillna(value={'x_1': 'not existed',}, axis=0, inplace=True)

【讨论】:

    猜你喜欢
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 2019-01-02
    • 2020-04-12
    • 1970-01-01
    • 2013-06-10
    相关资源
    最近更新 更多