【问题标题】:How to convert a string value in dataframe to float如何将数据框中的字符串值转换为浮点数
【发布时间】:2023-03-12 10:48:01
【问题描述】:

我有一个 csv 文件,我必须清理数据。问题是我可以通过 df.fillna() 填充空值,但字符串中有一些连续数字需要转换为 float 或 int 以便进一步计算。 我尝试了几种方法,但找不到解决方案。 请提供帮助,因为我是数据科学领域的新手,可能在提问时犯了一些错误。

此列有一个字符串值:df['hum'][316] = '64.70'

type(df['hum'][316]) = str

我将字符串值存储到一个变量中,然后使用 float(value) 但它给出了错误。

value = df['hum'][316]
>>>' "64.70"'
type(value)
>>> str
float(value)
>>>ValueError: could not convert string to float: ' "64.70"'


ValueError: could not convert string to float: ' "64.70"'

【问题讨论】:

  • 它看起来像你的字符串作为前导空格,这是正确的吗?试试df['hum'].str.lstrip().astype(float)
  • 感谢您的回复兄弟,我试过了,它给出了一个错误:无法将字符串转换为浮点数:'"64.70"'
  • 你好像嵌入了双引号,试试df['hum'].str.strip().str.replace('"','').astype(float)
  • 数据集中已经提供了双引号,我可以通过简单的方式修复它,但我希望 python 做到这一点,其次在尝试上面的代码后我得到: ValueError: could not convert string to float :
  • 好的,所以现在我们有很多人无法重现您的错误,在这个阶段您需要发布您的实际数据和代码,以便其他人帮助您,而不是浪费时间

标签: python-3.x pandas dataframe type-conversion


【解决方案1】:

df['hum'][316] = float(df['hum'][316])

【讨论】:

  • 见鬼!!!!非常感谢你。我以前尝试过这些东西,但以前没有用。
【解决方案2】:

似乎问题在于字符串中的",使用正则表达式将其删除

import re
value = df['hum'][316]
value=re.sub('"','',value)
float(value)

除了浮动,还可以检查 astype 是否适用于整个 df 或系列(列)的强制转换操作

如果您想将 df 的整个列更改为浮点数,请尝试:

df['hum'] = df['hum'].str.replace('"', '')
df['hum']=df['hum'].astype('float') 

问候朱利奥

【讨论】:

  • 嘿 Giulio,我之前在编程中没有使用过 re 模块,但我印象深刻的是它的工作原理,但在数据框中它仍然显示为字符串。请帮助
  • 修改数据框试试(也许有最好的选择):df['hum'][316]=float(re.sub('"','',df['hum'] [316]))
  • 它给出了这个错误:TypeError: expected string or bytes-like object
  • ValueError: 无法将字符串转换为浮点数:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-25
  • 2019-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-15
相关资源
最近更新 更多