python - 如何在 Pandas 中将 varchar 转换为 int/float
问题描述
我的数据来自mysql
表格。
id,revenue,cost,state
是varchar
列。
我需要为仅状态的分类变量执行 get_dummies(一种热编码)
如果它直接从
csv
(pd.read_csv) 读取,我将获得id,revenue,cost
作为 int/float 和state
作为对象的 dtypes
我的问题是如何将对象转换为 int64/float 如果它的数字和对象用于类别变量
- 有
strange
可能出现类似 ?,- 的字符可能会出现在收入中,但我仍然希望此列是数字
我做了什么
- 要立即解决此
varchar
问题,请直接将数据库中的 int 更改为问题得到修复
但我需要在熊猫中做
df.apply(pd.to_numeric, errors='coerce').fillna(df)
仍然是我的 int/float 列,例如id,revenue,cost
没有改变 dtype
解决方案
我认为首先是必要的测试 dtypes 之后pd.read_csv
:
print (df.dtypes)
然后将列转换为数字,但不能将缺失值替换为原始值,因为获取混合值 - 带字符串的数字:
cols = ['id','revenue','cost']
df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
推荐阅读
- bash - AWS CodeBuild,buildspec.yml“错误替换”错误
- python - 我们如何使用动态 SQL 从 Teradata 中提取数据,使用 Python 执行查询?
- mongodb - 在docker中运行nginx和mongodb,如何反向代理到mongodb?
- while-loop - CS50 Pset1/现金。虽然循环不承认平等
- python - 如何使用 Graph API 获取 Facebook 群组发布的所有帖子 ID?
- node.js - 使用jsforce,协商OAUTH2流程后,获取刷新&访问令牌,但不能使用
- google-sheets - Google工作表中重复项的单元格地址和值
- amazon-iam - AWS EKS:无法将 IAM 角色附加到 pod
- firebase - 有没有办法让谷歌云功能知道它在 Firebase 模拟器中运行?
- python - LazyLoadImages 和 Beautifulsoup 网页抓取