Best way to initialize and fill an numpy array?
我想初始化并填充一个
如我所料:
1 2 3 | >>> import numpy as np >>> np.empty(3) array([ -1.28822975e-231, -1.73060252e-077, 2.23946712e-314]) |
但这并不是:
1 2 | >>> np.empty(3).fill(np.nan) >>> |
没有什么?
1 2 | >>> type(np.empty(3)) <type 'numpy.ndarray'> |
在我看来,
先把
1 2 3 4 | >>> a = np.empty(3) >>> a.fill(np.nan) >>> a array([ nan, nan, nan]) |
为什么我需要给变量赋值才能使用
你也可以尝试
ZZU1
The relevant doc:
1 2 3 | Definition: np.full(shape, fill_value, dtype=None, order='C') Docstring: Return a new array of given shape and type, filled with `fill_value`. |
Although I think this might be only available in numpy 1.8+
修改阵列在位置,并返回
另一个选择是使用一个表达式,返回
1 | a = np.empty(3) * np.nan |
我觉得这很容易记起来:
1 | numpy.array([numpy.nan]*3) |
我不好奇,我是时候回答了,而且@joshadel's answer and@shx2's answer are faster than mine with large arrays.
1 2 3 4 5 6 7 8 | In [34]: %timeit -n10000 numpy.array([numpy.nan]*10000) 10000 loops, best of 3: 273 μs per loop In [35]: %timeit -n10000 numpy.empty(10000)* numpy.nan 10000 loops, best of 3: 6.5 μs per loop In [36]: %timeit -n10000 numpy.full(10000, numpy.nan) 10000 loops, best of 3: 5.42 μs per loop |
Just for future reference,the乘法by
最好的选择将是
1 2 3 4 5 6 7 8 9 10 11 | %timeit x = np.full((1000, 1000, 10), 432.4) 8.19 ms ± 97.8 μs per loop (mean ± std. dev. of 7 runs, 100 loops each) %timeit x = np.zeros((1000, 1000, 10)) + 432.4 9.86 ms ± 55.1 μs per loop (mean ± std. dev. of 7 runs, 100 loops each) %timeit x = np.ones((1000, 1000, 10)) * 432.4 17.3 ms ± 104 μs per loop (mean ± std. dev. of 7 runs, 100 loops each) %timeit x = np.array([432.4] * (1000 * 1000 * 10)).reshape((1000, 1000, 10)) 316 ms ± 37.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) |