首页 > 解决方案 > 如何在 Pandas 中将 varchar 转换为 int/float

问题描述

我的数据来自mysql表格。

id,revenue,cost,statevarchar列。

我的问题是如何将对象转换为 int64/float 如果它的数字和对象用于类别变量

我做了什么

但我需要在熊猫中做

df.apply(pd.to_numeric, errors='coerce').fillna(df) 仍然是我的 int/float 列,例如id,revenue,cost没有改变 dtype

标签: pythonpandas

解决方案


我认为首先是必要的测试 dtypes 之后pd.read_csv

print (df.dtypes)

然后将列转换为数字,但不能将缺失值替换为原始值,因为获取混合值 - 带字符串的数字:

cols = ['id','revenue','cost']
df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')

推荐阅读