[英]Pandas dataframe: convert column to number with default value
I'm surprised I couldn't find anything about this:我很惊讶我找不到任何关于此的信息:
Q: How can I convert values of a column to numbers with a default value if casting fails.问:如果转换失败,如何将列的值转换为具有默认值的数字。
I need all values to be numbers in order to perform arithmetical functions on them.我需要所有值都是数字,以便对它们执行算术函数。 The raw input data contains non-convertible values like
""
, "**"
, "not available"
, ....原始输入数据包含不可转换的值,例如
""
、 "**"
、 "not available"
,...。
Eg例如
1
2
*
4
Should become:应该变成:
1
2
0
4
What I've tried:我试过的:
to_numberic
: Does not allow to set a default value. to_numberic
:不允许设置默认值。 errors=coerce
will set the value to NaN
, which can not be handled arithmetically afterwards. errors=coerce
会将值设置为NaN
,之后无法进行算术处理。df[COLUMN].apply (makeNumber)
with def makeNumber(value): return 0.0
does apparently nothing on the string values. df[COLUMN].apply (makeNumber)
with def makeNumber(value): return 0.0
显然对字符串值没有任何作用。If no missing values in original use:如果原始使用中没有缺失值:
df['col'] = pd.to_numeric(df['col'], errors='coerce').fillna(0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.