python - 在进行数据帧操作之前,我可以让熊猫转换 dtypes 吗?
问题描述
假设我有一个具有多种 dtype 的 pandas 数据框,并且我想从另一个可能具有其他类型的数据中添加数据。有没有一种简单的方法可以让 pandas 转换类型或在例如连接数据帧时引发错误?
import pandas as pd
old = pd.DataFrame({'one':[1,2,3],'two':[100,200,300]}).astype({'one':'int8', 'two':'Int16'})
new = pd.DataFrame({'one':['11','22','33'],'two':['110','220','330']})
(old.dtypes == new.dtypes).all() # False
# a normal pd.concat([old, new]) at this point would result in 'object' dtypes for
# both columns. I want something like
result = coercive_concat([old, new])
(old.dtypes == result.dtypes).all() # True
(result.dtypes == new.dtypes).all() # False
# and it should raise an error when it can't coerce the types
odd = pd.DataFrame({'one':['eleventeen','22','33'],'two':['110','220','330']})
result = coercive_concat([old, odd]) # Error
解决方案
尝试:
new=new.astype(dict(zip(new.columns, old.dtypes.astype(str).str.lower().values)))
现在,如果您打印new.dtypes
,您将获得:
one int8
two int16
dtype: object
推荐阅读
- flask - Flask Gunicorn 共享令牌验证多个工作人员
- javascript - 无法显示验证码图像。获取方形缩略图而不是验证码图像(核心 PHP)
- javascript - 有什么方法可以读取在 JS 中以编程方式打印到控制台的内容?(用于检测)
- javascript - 如何传递反应列表项以作为 onClick 的参数
- python - 在 ctypes 中部分定义 Struct 定义
- javascript - D3 JS条形图,在条形顶部显示y轴标签值
- design-patterns - 没有 dbcontext 时的工作单元模式
- javascript - 如何从给定的外部 url 获取数据 Seesion id 和所有,而不是来自我的应用程序(路由)在 Angular 6
- xamarin - xamarin.ios 在外部单击时不会关闭 UIAlertController
- c# - 有没有办法从 ASP.NET Core IFileProvider 类中检索 HttpContext?