【问题标题】:could not convert string to float - object type无法将字符串转换为浮点数 - 对象类型
【发布时间】:2021-12-11 07:02:09
【问题描述】:

我正在使用 Pandas 和 Jupyter Notebook 在 Python 中处理数据框,我的数据框有经度和纬度列,其值类似于“-23,4588”。不知何故,每次我尝试将其转换为浮点数时,我都会收到一条错误消息,提示“无法将字符串转换为浮点数”。

我尝试更改逗号,尝试将 .csv 列类型更改为浮动,但没有任何效果。

我的代码的一部分:

ValueError                                Traceback (most recent call last)
C:\TEMP/ipykernel_12640/4061618161.py in <module>
----> 1 newocorr_sjc['Latitude'] = newocorr_sjc['Latitude'].astype(float)

c:\users\caique.fernandes\appdata\local\programs\python\python39\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 

c:\users\caique.fernandes\appdata\local\programs\python\python39\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(

c:\users\caique.fernandes\appdata\local\programs\python\python39\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:

c:\users\caique.fernandes\appdata\local\programs\python\python39\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

c:\users\caique.fernandes\appdata\local\programs\python\python39\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: '-23,5327'```

【问题讨论】:

  • -23,5327 应该是 -23.5327。如果你解决了这个问题,你将能够将其转换为 float 类型。

标签: python pandas dataframe csv jupyter-notebook


【解决方案1】:

也许你应该使用decimal=',' 作为pd.read_csv 的参数:

df = pd.read_csv('data.csv', sep=';', decimal=',')
>>> df.select_dtypes(float)
     17       22       23
0  17.5 -23.5327 -46.8182
1  56.3 -23.4315 -47.1269

【讨论】:

  • 两个选项都试过了,都没有用..
  • 您能否分享一个无法正常工作的 csv 文件示例?
  • 30427;4284;2021;30/09/2021;30/09/2021;Rodovias;30;9;SETEMBRO;2021;2021.09;QUINTA;03:50:00;MADRUGADA;CARAPICUIBA; Metropolitana de São Paulo;SP 021;17,5;ESTADUAL;CONCESSIONÁRIA-ARTESP;CCR RODOANEL;PUBLICO;-23,5327;-46,8182;CAMINHAO;CONDUTOR;VIA;COLISAO;TRASEIRA;MASCULINO;50-54;54 ;CAMINHAO;Até 30 dias 120514;1766;2021;30/09/2021;30/09/2021;Rodovias;30;9;SETEMBRO;2021;2021.09;QUINTA;16:55:00;TARDE;ARACARIGUAMA;Sorocaba; SP 280;56,3;ESTADUAL;CONCESSIONÁRIA-ARTESP;VIAOESTE;PUBLICO;-23,4315;-47,1269;MOTOCICLETA;CONDUTOR;ESTABELECIMENTO DE SAUDE;COLISAO;TRASEIRA;MASCULINO;30-34;33;CAMINHAO;Até 30 直径
  • @Caiiqef。我更新了我的答案。可以试试吗?
  • 它向我展示了唯一具有浮点类型的列,它不是长/纬度列..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多