问题描述
我想创建一个数组,该数组最初由相同的元组填充,特别是由 NaN
的元组填充。
例如,
I would like to create an array which is filled with identical tuples initially, specifically with tuples of NaN
.E.g.,
array([[(nan, nan), (nan, nan)],
[(nan, nan), (nan, nan)],
[(nan, nan), (nan, nan)]], dtype=object)
但是,当使用列出的数组初始化时,例如,其中包含一个可迭代的值作为填充数组的值, python
显然试图将可迭代的形状重塑到新数组中而不是用新数组填充:
However, when using the array initialisations listed e.g. here with an iterable value as value for filling in array, python
apparently tries to reshape that iterable into the new array rather than fill it with it:
np.full([3,2],(np.nan,np.nan,np.nan),dtype=tuple)
#ValueError: could not broadcast input array from shape (3) into shape (3,2)
np.fill
也不起作用,它
是否只能逐项填充数组?
Is it only possible to fill the array item by item?
推荐答案
您可以使用正确的 dtype
。使用'f,f'
,您可以使用 floats
的元组来初始化数组;有关更多信息,请参见。
You can, with the correct dtype
. With 'f,f'
you can initialise the array with tuples of floats
; see Data type objects (dtype) for more.
np.full((3,2), np.nan, dtype='f,f')
array([[(nan, nan), (nan, nan)],
[(nan, nan), (nan, nan)],
[(nan, nan), (nan, nan)]], dtype=[('f0', '<f4'), ('f1', '<f4')])
这篇关于用元组初始化NumPy数组(用相同的元组填充)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!