python numpy 如何生成一列都是nan的数组

我们大概都知道可以用 np.zeros 生成一列都是0的数组,用 np.ones生成一列都是1的数组,但是如果我想生成一列都是nan的数组呢?找了好久都没看到相应的函数,后来发现了另一个神奇的函数可以实现!

numpy.full(shape, fill_value, dtype=None, order=’C’)

Return a new array of given shape and type, filled with fill_value.

Parameters:
shape : int or sequence of ints
Shape of the new array, e.g., (2, 3) or 2.
fill_value : scalar
Fill value.
dtype : data-type, optional
The desired data-type for the array The default, None, means
np.array(fill_value).dtype.
order : {‘C’, ‘F’}, optional
Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory.
Returns:
out : ndarray
Array of fill_value with the given shape, dtype, and order.

生成5*1的数组,元素全为nan

import numpy as np

In [9]: np.full([1,5], np.nan)
Out[9]: array([[nan, nan, nan, nan, nan]])

np.full可以按照你制定的数据类型来生成数组,除了np.nan, 还可以是 数字,np.inf 等

In [10]: np.full((2, 2), np.inf)
Out[10]: 
array([[inf, inf],
       [inf, inf]])

In [11]: np.full((2, 2), 10)
Out[11]: 
array([[10, 10],
       [10, 10]])

其他数组初始化赋值函数也可以记忆一下

See also

  • zeros_like : Return an array of zeros with shape and type of input.
  • ones_like : Return an array of ones with shape and type of input.
  • empty_like: Return an empty array with shape and type of input.
  • full_like : Fill an array with shape and type of input.
  • zeros : Return a new array setting values to zero.
  • ones : Return a new array setting values to one.
  • empty: Return a new uninitialized array.

猜你喜欢

转载自blog.csdn.net/AlanGuoo/article/details/79919384
今日推荐