【问题标题】:Pandas: astype error string to float (could not convert string to float: '7,50')Pandas:astype 错误字符串为浮点数(无法将字符串转换为浮点数:'7,50')
【发布时间】:2020-06-03 02:29:57
【问题描述】:

我正在尝试将数据框字段从字符串转换为 Pandas 中的浮点数。

这是字段:

In:

print(merged['platnosc_total'].head(100))

Out:

0     0,00
1     4,50
2     0,00
3     0,00
4     0,00
5     4,50
6     6,10
7     7,99
8     4,00
9     7,69
10    7,50

注意最后一行的 7,50,这似乎会导致错误:

In: 

merged['platnosc_total'].astype(float)

Out:

ValueError: could not convert string to float: '7,50'

这是否意味着其余的都被转换了,只有 7,50 的行是原因?

我怎样才能真正将此字段/列转换为浮动?

【问题讨论】:

标签: python pandas


【解决方案1】:

首先需要replace

print (merged['platnosc_total'].replace(',','.', regex=True).astype(float))
0    0.00
1    4.50
2    0.00
3    0.00
4    0.00
5    4.50
6    6.10
7    7.99
8    4.00
Name: platnosc_total, dtype: float64

【讨论】:

  • 谢谢。我对我的 Excel 产生了偏见,它使用“,”表示十进制而不是“。” - 非英文版。
  • 如果使用read_excel 有没有自动转换?我只是好奇。
  • 我认为有,但我是从一个 csv 文件导入的,该文件使用“,”存储值。我所说的偏差的意思是,我假设昏迷适用于浮点数,我有一些带有点“。”的值。我什至将其替换回逗号,假设因为我的 Excel 使用逗号作为浮点数,我应该在其中有“,”,因此我很惊讶当文本值处于良好的转换状态时会出现错误。
【解决方案2】:

如果您的列中有nan 或空行,astype(float) 将不起作用。

你应该试试

merged.replace('', np.nan).dropna(subset=['platnosc_total'], inplace=True)
merged['platnosc_total'].astype(float)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 2019-08-15
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多