pandas ValueError: could not convert string to float: (dataframe string 转 float)(object 转 float)

在处理CSV数据时遇到问题,部分列以object格式存储字符串,包含空值。目标是将这些object列转换为float类型。通过参考文章‘在Pandas中更改列的数据类型【方法总结】’并利用Google搜索,成功解决了ValueError: could not convert string to float的错误,实现了数据类型的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

搞了一下午,终于把字符串转化成了数值

灵感来源:在Pandas中更改列的数据类型【方法总结】 - 纯净天空

顺便提一下,Google搜索就是比baidu有效率!

问题:pandas 导入 csv文件之后,有部分列是空的,列的类型为object格式,列中单元格存的是string格式

需求:把空的列(object)转化成浮点类型(float)

方法:

# 读取文件
data = pd.read_csv("./data/data.csv", encoding='utf-8')

# 我的表格前两列信息没有用,丢掉
data = data.ix[:, 2:]

# 找到列名,转化为列表
col = list(data.columns)

# 把所有列的类型都转化为数值型,出错的地方填入NaN,再把NaN的地方补0
data[col] = data[col].apply(pd.to_numeric, errors='coerce').fillna(0.0)
# 至此,object的列(列中存储的是string类型)转成了float

# 最后一步,把所有列都转化成float类型,done!
data = pd.DataFrame(data, dtype='float')

ValueError Traceback (most recent call last) Cell In[34], line 2 1 plt.figure(figsize=(7,4)) ----> 2 sns.heatmap(iris.corr(),annot=True,cmap='cubehelix_r') 3 plt.show() File D:\anaconda3\Lib\site-packages\pandas\core\frame.py:11049, in DataFrame.corr(self, method, min_periods, numeric_only) 11047 cols = data.columns 11048 idx = cols.copy() > 11049 mat = data.to_numpy(dtype=float, na_value=np.nan, copy=False) 11051 if method == "pearson": 11052 correl = libalgos.nancorr(mat, minp=min_periods) File D:\anaconda3\Lib\site-packages\pandas\core\frame.py:1993, in DataFrame.to_numpy(self, dtype, copy, na_value) 1991 if dtype is not None: 1992 dtype = np.dtype(dtype) -> 1993 result = self._mgr.as_array(dtype=dtype, copy=copy, na_value=na_value) 1994 if result.dtype is not dtype: 1995 result = np.asarray(result, dtype=dtype) File D:\anaconda3\Lib\site-packages\pandas\core\internals\managers.py:1694, in BlockManager.as_array(self, dtype, copy, na_value) 1692 arr.flags.writeable = False 1693 else: -> 1694 arr = self._interleave(dtype=dtype, na_value=na_value) 1695 # The underlying data was copied within _interleave, so no need 1696 # to further copy if copy=True or setting na_value 1698 if na_value is lib.no_default: File D:\anaconda3\Lib\site-packages\pandas\core\internals\managers.py:1753, in BlockManager._interleave(self, dtype, na_value) 1751 else: 1752 arr = blk.get_values(dtype) -> 1753 result[rl.indexer] = arr 1754 itemmask[rl.indexer] = 1 1756 if not itemmask.all(): ValueError: could not convert string to float: 'Iris-setosa'
最新发布
06-21
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值