如何在数据帧中将对象转换为浮点

2024-03-28 23:46:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我在每列中都有一个数据框,我有数字,但类型是object!如何将对象转换为浮点

我试过这个: pd.to_numeric(df['Close_x'],errors='coerce')

但错误是:

TypeError: arg must be a list, tuple, 1-d array, or Series

我试过concatenated['Close_x'].astype(float)

错误显示:

ValueError: could not convert string to float: '1,001.96'


Tags: to数据对象类型dfcloseobject错误
1条回答
网友
1楼 · 发布于 2024-03-28 23:46:52

这些数字以,作为分隔符,因此首先需要将其替换为空字符串,然后将其转换为浮点数

df = pd.DataFrame(['1,001.96', '1001.98'], columns=['value'])
pd.to_numeric(df['value'].replace(',', '',regex=True))

df.apply(lambda x: x.str.replace(',', '')).astype(float)

注意:df.apply对于大数据帧比pd.to_numeric

相关问题 更多 >