【问题标题】:How to convert numeric strings with period separators to float?如何将带有句点分隔符的数字字符串转换为浮点数?
【发布时间】:2020-09-02 18:08:18
【问题描述】:

我正在尝试将 Pandas DataFrame 中的值从字符串转换为浮点数,但遇到了错误。

该列如下所示:

PIB (IBGE/2005)
---------------
 71.638.000
114.250.000
 44.373.000
462.258.000
186.812.000

其中. 是数字组分隔符,所以71.638.000 应该变成浮点数71638000

但我得到了错误:

ValueError: could not convert string to float: '71.638.000'

这是我的完整 DataFrame 的图像:

如何将此列从字符串转换为浮点数?

【问题讨论】:

  • 71.638.000 应该是什么浮点数?
  • 看起来你的数据集中的字符.是千位分隔符,这混淆了你的解析库(可能默认设置为将.理解为英文小数点)。我建议清理您的数据以删除那些 .
  • @Pac0 也许问题真的是千位分隔符,我会检查一下。谢谢
  • 使用pd.read_csv(yourfile, thousands='.')pd.to_numeric(df[column])
  • 这能回答你的问题吗? Pandas: convert dtype 'object' to int

标签: python pandas


【解决方案1】:

“PIB (IBGE/2005)”列中的值似乎有一个作为千位分隔符的句点。在将值转换为浮点数之前,您必须删除它们。您可以尝试按照以下方式尝试将列转换为浮点数:

df1 = df1['PIB (IBGE/2005)'].apply(lambda x: x.replace('.', ''))

编辑: 正如下面的 cmets 建议的那样,作为avoid apply

的更正确解决方案
df1 = df1['PIB (IBGE/2005)'].str.replace('.', '')

【讨论】:

  • 或者使用 pandas 的字符串方法之一:df1 = df1['PIB (IBGE/2005)'].str.replace('.', '')
  • 当你有可以使用的方法时,不要使用apply
  • 成功了,问题出在千位分隔符的句号上……非常感谢所有做出贡献的人
【解决方案2】:

替换“。” with '' 并将字符串转换为浮点数

S = "123.567.000"
D = float(S.replace('.',''))
print(D)

【讨论】:

    猜你喜欢
    • 2019-06-03
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多