无法将 'str' 转换为 Python 3.0 中的数值
Can't convert 'str' to numerical value in Python 3.0
我是一个新的 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'
。其他人可能会失败,因为数字字符串中包含逗号。
感谢大家的回答!他们确实引导我找到了解决方案。
我最后做的是
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'。
我是一个新的 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'
。其他人可能会失败,因为数字字符串中包含逗号。
感谢大家的回答!他们确实引导我找到了解决方案。 我最后做的是
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'。