在 Pandas (Python 3) 中用 0 替换 WhiteSpace
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25586085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace WhiteSpace with a 0 in Pandas (Python 3)
提问by user3682157
simple question here -- how do I replace all of the whitespaces in a column with a zero?
这里有一个简单的问题——如何用零替换列中的所有空格?
For example:
例如:
Name Age
John 12
Mary
Tim 15
into
进入
Name Age
John 12
Mary 0
Tim 15
I've been trying using something like this but I am unsure how Pandas actually reads whitespace:
我一直在尝试使用这样的东西,但我不确定 Pandas 实际上是如何读取空格的:
merged['Age'].replace(" ", 0).bfill()
Any ideas?
有任何想法吗?
回答by EdChum
Use the built in method convert_objectsand set param convert_numeric=True:
使用内置方法convert_objects并设置 param 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
回答by paulo.filip3
merged['Age'] = merged['Age'].apply(lambda x: 0 if x == ' ' else x)
回答by Patrick Collins
Here's an answer modified from this, more thorough question. I'll make it a little bit more Pythonic and resolve your basestringissue.
这是从这个更彻底的问题修改而来的答案。我会让它更 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)
where dis your dataframe.
d你的数据框在哪里。

