【发布时间】: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() 来转换列的数据类型。我知道的目标数据类型的两种可能性是:int 和 pd.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