在熊猫(>1.0)中,如何将具有缺失值的浮点序列的dtype转换为整数?

  • 本文关键字:整数 转换 dtype 熊猫 python pandas
  • 更新时间 :
  • 英文 :


转换Series数据类型很容易:

s = pd.Series([1.1, 2.2]).astype(int)

但是,如果Series contains apd.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值(或使用ceilingfloor(,然后转换为pd.Int64Dtype()(拒绝转换非整数值(

s = pd.Series([1.1, 2.2, None])
s.round().astype(pd.Int64Dtype())

最新更新