Python 无法将pandas.read\u excel中的字符串转换为数字
问题 我有一个德文格式的excel文件。看起来像这样 我想使用流动代码将第一列作为数字读入熊猫:Python 无法将pandas.read\u excel中的字符串转换为数字,python,pandas,Python,Pandas,问题 我有一个德文格式的excel文件。看起来像这样 我想使用流动代码将第一列作为数字读入熊猫: import pandas as pd import numpy as np tmp = pd.read_excel("test.xlsx", dtype = {"col1": np.float64}) 这给了我一个错误 ValueError: Unable to convert column col1 to type <class 'numpy.f
import pandas as pd
import numpy as np
tmp = pd.read_excel("test.xlsx", dtype = {"col1": np.float64})
这给了我一个错误
ValueError: Unable to convert column col1 to type <class 'numpy.float64'>
ValueError:无法将列col1转换为类型
该问题以excel格式发布。如果我手动将col1
manuelly修改为数字格式,问题就解决了。查看此新excel文件:
方法
我可以先将col1
作为对象读取到pandas中,然后我需要将,
替换为,
,最后我可以将字符串更改为float
但是
这种方法很乏味。如何才能更有效地解决此问题?不幸的是,无法告诉熊猫正在使用哪种十进制分隔符 不过,您可以创建一个函数来进行转换,并将其作为converters参数的一部分传递给read_excel
def fix_decimal(num):
### convert numeric value with comma as decimal separator to float
print(num)
return float(num.replace(',', '.')) if num else 0
tmp = pd.read_excel("test.xlsx", converters={0: fix_decimal} )
也许这个答案会对你有所帮助