无法将字符串转换为 pandas 中的浮点数(ValueError)

问题描述 投票:0回答:4

我有一个从 JSON 输出创建的数据框,如下所示:

        Total Revenue    Average Revenue    Purchase count    Rate
Date    
Monday  1,304.40 CA$     20.07 CA$          2,345             1.54 %

存储的值作为字符串从 JSON 接收。我正在努力:

1) 删除条目中的所有字符(例如:CA$ 或 %) 2) 将费率和收入列转换为浮动值 3)将计数列转换为int

我尝试执行以下操作:

df[column] = (df[column].str.split()).apply(lambda x: float(x[0]))

它工作得很好,除非我有一个带有昏迷的值(例如:1,465 不起作用,而 143 则可以)。

我尝试使用几个函数来替换“,”为“”等。到目前为止没有任何效果。我总是收到以下错误:

ValueError:无法将字符串转换为浮点数:'1,304.40'

python json pandas dataframe numeric
4个回答
18
投票

这些字符串以逗号作为千位分隔符,因此您必须在调用

float
:

之前删除它们
df[column] = (df[column].str.split()).apply(lambda x: float(x[0].replace(',', '')))

这可以通过将

split
移动到
lambda
内来简化一点:

df[column] = df[column].apply(lambda x: float(x.split()[0].replace(',', '')))

4
投票

另一个具有

list
理解的解决方案,如果需要,请应用
string
functions 仅适用于
Series
DataFrame
的列),如
str.split
str.replace
:

df = pd.concat([df[col].str.split()
                       .str[0]
                       .str.replace(',','').astype(float) for col in df], axis=1)

#if need convert column Purchase count to int
df['Purchase count'] = df['Purchase count'].astype(int)
print (df)
         Total Revenue  Average Revenue  Purchase count  Rate
Date                                                        
Monday         1304.4            20.07            2345  1.54

1
投票

我也遇到过这个问题,并且使用下面的代码解决了我的问题:

import pandas as pd
df['Purchase count'] = pd.to_numeric(df['Purchase count'], errors='coerce')
print(df.dtypes)

0
投票

以下解决方案对我有用..!!

import pandas as pd


df['Purchase count'] = df['Purchase count'].replace(',', '', regex=True).astype(float)

print('type:    ', type(df['Purchase count']))
© www.soinside.com 2019 - 2024. All rights reserved.