【问题标题】:Pandas: Casting a float column to int while also keeping the NaNs [duplicate]Pandas:将浮点列转换为 int,同时保留 NaN [重复]
【发布时间】:2020-12-30 21:55:27
【问题描述】:

我有这样的数据:

df = pd.DataFrame({ 'val1': [5.3, np.nan, 2.0, 1.2, 5]})
print(df)

   val1
0   5.3
1   NaN
2   2.0
3   1.2
4   5.0

我知道我可以使用astype() 来转换列的数据类型。我知道的目标数据类型的两种可能性是:intpd.Int64Dtype()

但是,对于 int,我对 NaN 值有疑问(我确实想保留 NaN,而不是用任何其他值填充它们):

df = df.astype({'val1': 'int'})

ValueError: Cannot convert non-finite values (NA or inf) to integer

而对于 pd.Int64Dtype(),我有一个浮点值问题,必须将其转换为 int:

df = df.astype({'val1':pd.Int64Dtype()})

TypeError: cannot safely cast non-equivalent float64 to int64

如何将浮点数转换为整数并保留 NaN?

【问题讨论】:

  • 你不能这样做,因为NaNs 的类型是浮点数,而不是整数。您当然可以将数字四舍五入为整数,但只要列中有NaN,它将保持dtype = float

标签: python pandas type-conversion


【解决方案1】:

编辑:我误解了这个问题,

def cast(x):
    try:
        return float(x)
    except ValueError:
        return None

df = df.apply(cast)

【讨论】:

  • OP 想要 NaN,而不是 0。平均值、中位数或任何运算都会提供不同的值。
  • 哦,我以为问题是别的,现在呢?对吗?
猜你喜欢
  • 2017-03-20
  • 1970-01-01
  • 2021-12-18
  • 2012-05-09
  • 1970-01-01
  • 2020-01-21
  • 1970-01-01
  • 2014-05-09
  • 1970-01-01
相关资源
最近更新 更多