无法在 Python 3.0 中将“str”转换为数值

问题描述

我是一个新的 Python 编码员,对我来说太赤裸裸了。我想将某些列从“str”转换为“int”或“float”。但是,无论我对列应用什么代码(pd.to_numerical、astype(int) 等),它总是给我错误或数字仍然显示为“str”。这是我要使用的 I 代码类型的示例:

data = pd.read_csv('...xyz')

cols = data.columns[7:13]
for i in cols:
data[i] = data[i].str.strip()
data[i] = data[i].apply(pd.to_numeric,errors='coerse').fillna(0) -->This code gives me "ValueError: invalid error value specified"

data[i] = data[i].astype('float64') -->This code gives me "ValueError: Could not convert string to float: '77,830'"

data[i] = data[i].astype(int) -->This code gives me "ValueError: cannot convert float NaN to integer"

起初,我认为这是数字中的空格问题,但即使我去掉它们,问题仍然存在。我错过了什么???任何建议将不胜感激!

解决方法

在第一次尝试时,errors='coerse' 应该是 errors='coerce'。其他人可能会失败,因为数字字符串中包含逗号。

,

谢谢大家的回答!他们 defo 引导我找到解决方案。 我最终做的是

data = pd.read_csv('...xyz',thousands=',')

有趣的是,修复了我想要修复的 4 列中的 2 列,因为它没有将逗号识别为千位。其余的我做了以下:

cols = data.columns[8:10]

for i in cols:
    data[i] = data[i].str.replace(',','')
    data[i] = data[i].str.strip()
    data[i] = data[i].apply(pd.to_numeric,errors='coerce').fillna(0)

'astype' 在这里也不起作用,所以我不得不做 'pd.to_numeric'。