python - 将带有逗号空格逗号的 CSV 转换为浮点型

标签 python pandas

我正在使用 pandas 在 python 中工作,最终想要运行一个随机森林。 Python 出现错误,因为我无法将这个带有空格的数字列作为空值转换为 float 。我尝试用零和 astype(float) 填充,但没有成功。谢谢大家!

    sm['PopHalfMile']
Out[64]:

0      2072
1      4392
2      2986
3          
4          
       ... 
281    3350
282    1481
283     607
284    4708
285    4237
Name: PopHalfMile, Length: 286, dtype: object
In [65]:

sm['PopHalfMile'].fillna(value=0)
Out[65]:

0      2072
1      4392
2      2986
3          
4          
       ... 
281    3350
282    1481
283     607
284    4708
285    4237
Name: PopHalfMile, Length: 286, dtype: object

So i looked at the csv file in notepad and their is a space where the data is null. ...comma space comma.

6, ,2103,



This is causing  me to get this error after trying to convert the field to a float.

sm["PopHalfMile"] = sm.PopHalfMile.astype(float)

ValueError: could not convert string to float: 

最佳答案

尝试使用replace()而不是fillna(),因为您尝试替换的值显然不是空值;它们是空格吗?

df = pd.read_csv(filename)
df.replace(" ", 0)

关于python - 将带有逗号空格逗号的 CSV 转换为浮点型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58862894/

相关文章:

python - 如果有人输入一个整数,答案中应该有一个字符串,我应该使用哪种错误类型?

python - 记录掷骰子游戏的输赢

python - Pandas 系列到 Pandas Dataframe

pandas - 悬停工具提示不适用于 Networkx Graph 的 Bokeh 可视化

python - 将文件夹中的多个 Excel 文件读取到 pandas 中

python - Pandas:通过提供标题名称来读取列

python - App Engine 开发服务器 sendmail 错误 - 想要抑制

python - 需要帮助理解这个 Python Viterbi 算法

python - 为什么 Amazon Linux 上的 .so 文件比 OS X 上的大 5 倍?

python - 将日期列和时间列合并为日期时间列