首页 > 解决方案 > 在进行数据帧操作之前,我可以让熊猫转换 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

标签: pythonpandasdataframe

解决方案


尝试:

new=new.astype(dict(zip(new.columns, old.dtypes.astype(str).str.lower().values)))

现在,如果您打印new.dtypes,您将获得:

one     int8
two    int16
dtype: object

推荐阅读