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

时间:2021-05-18 08:22:47

标签: python python-3.x pandas string floating-point

使用

更改为浮点数时
final.iloc[:,4:10]=final.iloc[:,4:10].replace(',', '.').astype(float)

我收到以下错误:

[ValueError                                Traceback (most recent call last)
<ipython-input-33-56c93743e023> in <module>
      1 final.dtypes
----> 2 final.iloc\[:,4:10\]=final.iloc\[:,4:10\].replace(',', '.').astype(float)

~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\generic.py in astype(self, dtype, copy, errors)
   5875         else:
   5876             # else, only a single dtype is given
-> 5877             new_data = self._mgr.astype(dtype=dtype, copy=copy, errors=errors)
   5878             return self._constructor(new_data).__finalize__(self, method="astype")
   5879 

~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\internals\managers.py in astype(self, dtype, copy, errors)
    629         self, dtype, copy: bool = False, errors: str = "raise"
    630     ) -> "BlockManager":
--> 631         return self.apply("astype", dtype=dtype, copy=copy, errors=errors)
    632 
    633     def convert(

~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\internals\managers.py in apply(self, f, align_keys, ignore_failures, **kwargs)
    425                     applied = b.apply(f, **kwargs)
    426                 else:
--> 427                     applied = getattr(b, f)(**kwargs)
    428             except (TypeError, NotImplementedError):
    429                 if not ignore_failures:

~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\internals\blocks.py in astype(self, dtype, copy, errors)
    671             vals1d = values.ravel()
    672             try:
--> 673                 values = astype_nansafe(vals1d, dtype, copy=True)
    674             except (ValueError, TypeError):
    675                 # e.g. astype_nansafe can fail on object-dtype of strings

~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\dtypes\cast.py in astype_nansafe(arr, dtype, copy, skipna)
   1095     if copy or is_object_dtype(arr) or is_object_dtype(dtype):
   1096         # Explicit copy, or required since NumPy can't view from / to object.
-> 1097         return arr.astype(dtype, copy=True)
   1098 
   1099     return arr.view(dtype)

ValueError: could not convert string to float: '86,5484466552734'][1]

由此可见

<块引用>

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

作为参考,这些是我正在使用的 df 列的数据类型(使用 df.dtypes

Country.Name                                                                              object
Country.Code                                                                              object
Year                                                                                       int64
Prevalence of stunting, height for age (% of children under 5)                            object
Trained teachers in lower secondary education, male (% of male teachers)                  object
Share of youth not in education, employment or training, total (% of youth population)    object
External debt stocks (% of GNI)                                                           object
Contributing family workers, male (% of male employment) (modeled ILO estimate)           object
Tax revenue (% of GDP)                                                                    object
Over-age students, primary, female (% of female enrollment)                               object
nans                                                                                       int64
dtype: object

1 个答案:

答案 0 :(得分:0)

您要做的是将 , 替换为 .,并且有多种方法可以做到这一点。

另一种选择是使用 applystr.replace

考虑到您想将更改应用于 final.iloc[:,4:10],以下内容可能会起作用

final.iloc[:,4:10] = final.iloc[:,4:10].apply(lambda col: col.str.replace(',', '.').astype(float))

另一个是在读取文件时,例如 CSV,假设使用的是 Pandas,则需要显式传递 decimals='.'