ValueError:无法解析位置 0 处的字符串“15,181.80”

Jac*_*itt 2 python pandas

我试图将 df 转换为所有数值,但出现以下错误。

ValueError: Unable to parse string "15,181.80" at position 0
Run Code Online (Sandbox Code Playgroud)

这是我当前的代码:

ValueError: Unable to parse string "15,181.80" at position 0
Run Code Online (Sandbox Code Playgroud)

在我尝试转换之前 df :

data = pd.read_csv('pub?gid=1704010735&single=true&output=csv',
                 usecols=[0,1,2], 
                 header=0,
                 encoding="utf-8-sig",
                 index_col='Date') 

data.apply(pd.to_numeric)

print("we have a total of:", len(data), " samples")

data.head()
Run Code Online (Sandbox Code Playgroud)

我认为问题在于它处理特殊字符 EG“,” - 这是正确的吗?帮助将 DF 转换为所有数值的最佳建议是什么?

谢谢!

You*_*dna 8

删除,数据帧中的所有数字将解决您的问题。

这是我使用的代码:

import pandas as pd

df = pd.DataFrame({'value':['10,000.23','20,000.30','10,000.10']})
   
df['value'] = df['value'].str.replace(',', '').astype(float)

df.apply(pd.to_numeric)

Run Code Online (Sandbox Code Playgroud)

输出:

      value
0  10000.23
1  20000.30
2  10000.10
Run Code Online (Sandbox Code Playgroud)

编辑:

您还可以使用:

df= df.value.str.replace(',', '').astype(float)
Run Code Online (Sandbox Code Playgroud)

value是您要转换的列