是否有一种首选的方法来保持numpy数组的数据类型固定为int(或int64或其他),同时仍然有一个元素列在numpy. nan中?

特别是,我正在将一个内部数据结构转换为Pandas DataFrame。在我们的结构中,我们有整数类型的列,这些列仍然有NaN(但是列的dtype是int)。如果我们把它设为DataFrame,它似乎把所有东西都重铸为浮点数,但我们希望它是int。

想法吗?

试过的东西:

我尝试在pandas下使用from_records()函数。DataFrame,与coerce_float=False,这没有帮助。我还尝试使用NumPy掩码数组,使用NaN fill_value,这也没有工作。所有这些都会导致列数据类型变成浮点数。


当前回答

从版本0.24开始,这个功能已经被添加到pandas中。

此时,它需要使用扩展dtype 'Int64'(大写),而不是默认的dtype 'Int64'(小写)。

其他回答

NaN不能存储在整数数组中。这是目前已知的熊猫的局限性;我一直在等待NumPy中NA值的进展(类似于R中的NA),但至少需要6个月到一年的时间NumPy才能获得这些功能,看起来:

http://pandas.pydata.org/pandas-docs/stable/gotchas.html#support-for-integer-na

(从pandas的0.24版本开始就添加了这个特性,但请注意,它需要使用扩展名dtype Int64(大写),而不是默认的dtype Int64(小写): https://pandas.pydata.org/pandas-docs/version/0.24/whatsnew/v0.24.0.html#optional-integer-na-support )

如果性能不是主要问题,则可以存储字符串。

df.col = df.col.dropna().apply(lambda x: str(int(x)) )

然后你可以和NaN任意混合。如果您确实希望使用整数,则可以根据您的应用程序使用-1、0、1234567890或其他专用值来表示NaN。

你也可以临时复制列:一个是你已经有的,用浮点;另一种是实验性的,使用int或字符串。然后在每个合理的位置插入断言,检查两者是否同步。经过足够多的测试后,你就可以放手了。

这不是所有情况下的解决方案,但我(基因组坐标)已经使用0作为NaN

a3['MapInfo'] = a3['MapInfo'].fillna(0).astype(int)

这至少允许使用适当的“本机”列类型,像减法,比较等操作可以正常工作

熊猫v1.00 +的新功能

您没有(也不能)使用numpy。再也不会了。 现在你有熊猫了。

请阅读:https://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html

IntegerArray is currently experimental. Its API or implementation may change without warning. Changed in version 1.0.0: Now uses pandas.NA as the missing value rather than numpy.nan. In Working with missing data, we saw that pandas primarily uses NaN to represent missing data. Because NaN is a float, this forces an array of integers with any missing values to become floating point. In some cases, this may not matter much. But if your integer column is, say, an identifier, casting to float can be problematic. Some integers cannot even be represented as floating point numbers.

从版本0.24开始,这个功能已经被添加到pandas中。

此时,它需要使用扩展dtype 'Int64'(大写),而不是默认的dtype 'Int64'(小写)。