转换Series
数据类型很容易:
s = pd.Series([1.1, 2.2]).astype(int)
但是,如果Series contains a
pd.NA`(N/A值(,则转换会中断
s = pd.Series([1.1, 2.2, pd.NA]).astype(int)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NAType'
中的结果
尽管事实上,我们可以将缺失的值存储在int 的Series
中
s = pd.Series([1, 2, pd.NA]).astype(pd.Int64Dtype())
我不确定这是一个变通方法还是一个实际的解决方案,但解决这个问题的一种方法是round
值(或使用ceiling
或floor
(,然后转换为pd.Int64Dtype()
(拒绝转换非整数值(
s = pd.Series([1.1, 2.2, None])
s.round().astype(pd.Int64Dtype())