是否有一种首选的方法来保持numpy数组的数据类型固定为int(或int64或其他),同时仍然有一个元素列在numpy. nan中?
特别是,我正在将一个内部数据结构转换为Pandas DataFrame。在我们的结构中,我们有整数类型的列,这些列仍然有NaN(但是列的dtype是int)。如果我们把它设为DataFrame,它似乎把所有东西都重铸为浮点数,但我们希望它是int。
想法吗?
试过的东西:
我尝试在pandas下使用from_records()函数。DataFrame,与coerce_float=False,这没有帮助。我还尝试使用NumPy掩码数组,使用NaN fill_value,这也没有工作。所有这些都会导致列数据类型变成浮点数。
如果您试图将浮点(1.143)向量转换为整数(1),并且该向量具有NAs,则将其转换为新的'Int64' dtype将会给您一个错误。为了解决这个问题,你必须四舍五入的数字,然后做".astype('Int64')"
s1 = pd.Series([1.434, 2.343, np.nan])
#without round() the next line returns an error
s1.astype('Int64')
#cannot safely cast non-equivalent float64 to int64
##with round() it works
s1.round().astype('Int64')
0 1
1 2
2 NaN
dtype: Int64
我的用例是,我有一个浮点系列,我想四舍五入到int,但当你做。round()仍然有小数,你需要转换为int删除小数。