Pandas中将DataFrame列类型Int64转换为int64的实现方法
问题原因
astype()方法不会对原DataFrame做原地修改,只会返回转换类型后的新对象,你没有将转换结果赋值回原列,所以原列的类型没有发生变化。- pandas 中的
Int64是支持空值的可空整数类型,如果该列存在pd.NA空值,直接转换为numpy原生的int64类型会抛出错误,需要先处理空值再执行转换。
正确实现方式
情况1:确认列中无空值
直接将转换结果赋值回原列即可:
import numpy as np print(region_ids.mycolumn.dtypes) region_ids['mycolumn'] = region_ids['mycolumn'].astype(np.int64) print(region_ids.mycolumn.dtypes)
输出结果会符合预期:
Int64 int64
情况2:列中存在空值
需要先对空值做填充/删除处理,再执行类型转换,比如将空值填充为0:
import numpy as np print(region_ids.mycolumn.dtypes) region_ids['mycolumn'] = region_ids['mycolumn'].fillna(0).astype(np.int64) print(region_ids.mycolumn.dtypes)
内容的提问来源于stack exchange,提问作者xzk
相关产品推荐
相关产品推荐

