从无值的Python INT列表初始化numpy的屏蔽数组 [英] Initializing numpy masked array from Python int list with None values
问题描述
如图中问题的答案<一href=\"http://stackoverflow.com/questions/19456239/convert-python-list-with-none-values-to-numpy-array-with-nan-values\">Convert与无值蟒蛇名单numpy的阵列NaN值,它是直接从具有无值的列表初始化一个蒙面numpy的数组,如果我们执行DTYPE =浮动。这些浮点值被转换为NaN,我们可以简单地做:
As shown in the answer to the question Convert python list with None values to numpy array with nan values, it is straightforward to initialize a masked numpy array from a list with None values if we enforce the dtype=float. Those float values get converted to nan and we can simply do:
ma.masked_invalid(np.array(a, dtype=float), copy=False)
这不过不会像INT工作:
This however will not work for int like:
ma.masked_invalid(np.array(a, dtype=int), copy=False)
由于中间np.array不会与没有值被创建(没有INT南)。
since the intermediate np.array will not be created with None values (there is no int nan).
什么是初始化基于整数的Python列表上一个蒙面的数组,也包含这样的方式,那些无值变为屏蔽无值的最有效方法是什么?
What is the most efficient way to initialize a masked array based on Python list of ints that also contains None values in such way that those None values become masked?
推荐答案
最优雅的解决方案到目前为止,我已经找到(它是不优雅可言)是初始化类型的屏蔽数组浮动
,并将其转换为 INT
算账:
The most elegant solution I have found so far (and it is not elegant at all) is to initialize a masked array of type float
and convert it to int
afterwards:
ma.masked_invalid(np.array(a, dtype=float), copy=False).astype(int)
这会产生一个适当的NP阵列初始阵列在无
值 A
被屏蔽。例如,对于
This generates a proper NP array where None
values in the initial array a
are masked. For instance, for:
a = [1, 2, 3, None, 4]
ma.masked_invalid(np.array(a, dtype=float), copy=False).astype(int)
我们得到:
masked_array(data = [1 2 3 -- 4],
mask = [False False False True False],
fill_value = 999999)
另外,实际蒙面INT值变得分钟INT,即
Also, the actual masked int values become min int, i.e.
ma.masked_invalid(np.array(column, dtype=float), copy=False).astype(int).data
给出了:
array([ 1, 2, 3,
-9223372036854775808, 4])
这篇关于从无值的Python INT列表初始化numpy的屏蔽数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!