用Pandas中的0替换WhiteSpace(Python 3)

时间:2014-08-30 19:39:07

标签: python pandas

这里的简单问题 - 如何用零替换列中的所有空格?

例如:

  Name       Age
  John       12
  Mary 
  Tim        15

  Name       Age
  John       12
  Mary       0
  Tim        15

我一直在尝试使用类似的东西,但我不确定Pandas究竟是如何读取空白的:

 merged['Age'].replace(" ", 0).bfill()

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

使用内置方法convert_objects并设置参数convert_numeric=True

In [12]:
# convert objects will handle multiple whitespace, this will convert them to NaN
# we then call fillna to convert those to 0
df.Age = df[['Age']].convert_objects(convert_numeric=True).fillna(0)
df
Out[12]:
   Name  Age
0  John   12
1  Mary    0
2   Tim   15

答案 1 :(得分:1)

这是从this, more thorough question修改的答案。我会把它变得更加Pythonic并解决你的basestring问题。

def ws_to_zero(maybe_ws):
    try:
        if maybe_ws.isspace():
            return 0
        else:
            return maybe_ws
    except AttributeError:
        return maybe_ws

d.applymap(ws_to_zero)

其中d是您的数据框。

答案 2 :(得分:1)

merged['Age'] = merged['Age'].apply(lambda x: 0 if x == ' ' else x)