【问题标题】:Could not convert string to float: '2.648.142' (Panda)无法将字符串转换为浮点数:“2.648.142”(熊猫)
【发布时间】:2020-11-25 10:55:09
【问题描述】:

我正在尝试将从 html 导入中获取的单个列从字符串转换为浮点数。 列(价格)包含一个货币符号,我试图用 '' 替换它。

import pandas as pd

Cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [2.648.142€,2500000€,2700000€,35000€]
        }

df = pd.DataFrame(cars, columns = ['Brand', 'Price'])


df['Price']=df['Price'].replace('€','', regex=True)

df['Price']= df['Price'].astype(float)

print (df)

错误:

ValueError:无法将字符串转换为浮点数:'2.648.142'

如果我使用

pd.to_numeric(df, errors='coerce')

错误:

TypeError: arg 必须是列表、元组、一维数组或系列

输出仅包括价格

【问题讨论】:

  • 2.648.142 应该是什么意思?我无法将其转换为自己浮动。
  • 也许您只需要将. 替换为空字符串?

标签: python pandas string


【解决方案1】:

您也可以将. 替换为空字符串,因为特殊的正则表达式字符会被\ 转义:

df['Price'] = df['Price'].replace('[€\.]','', regex=True).astype(float)
print (df)
            Brand      Price
0     Honda Civic  2648142.0
1  Toyota Corolla  2500000.0
2      Ford Focus  2700000.0
3         Audi A4    35000.0

【讨论】:

  • 您如何理解. 应该被删除(或至少被视为逗号)?仅仅通过与其他值的相似性?
  • @kabanus - 没错。
  • @kabanus - 也是因为The output only includes price < 1.000.000,
猜你喜欢
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多