使用Pandas(Python 3)将空格替换为0

2024-09-28 03:11:52 发布

您现在位置:Python中文网/ 问答频道 /正文

这里有一个简单的问题——如何用零替换列中的所有空白?

例如:

  Name       Age
  John       12
  Mary 
  Tim        15

进入

  Name       Age
  John       12
  Mary       0
  Tim        15

我一直在尝试这样的方法,但我不确定熊猫到底是如何读取空白的:

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

有什么想法吗?


Tags: 方法nameagemergedjohn空白replacetim
3条回答

使用内置方法^{}并设置参数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

这是从this, more thorough question修改的答案。我会让它更像Python,解决你的问题。

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是您的数据帧。

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

相关问题 更多 >

    热门问题