如何用另一个numpy数组填充numpy数组 [英] How to fill numpy array with another numpy array
问题描述
我有一个空的numpy数组,另一个有值。我想用填充的x填充空的numpy数组。
因此,当x = 3时,(最初为空的数组)看起来像 [[populated_array],[populated_array],[populated_array]]
I have an empty numpy array, and another one populated with values. I want to fill the empty numpy array with the populated one, x times.
So, when x = 3, the (originally empty array) would look like [[populated_array],[populated_array], [populated_array]]
其中populated_array每次都是相同的值/数组。
我已经尝试过
Where populated_array is the same value/array each time. I have tried this
a = np.empty(3)
a.fill(np.array([4,6,6,1]))
但是得到这个
ValueError: Input object to FillWithScalar is not a scalar
并想要这个
[[4,6,6,1],[4,6,6,1],[4,6,6,1]]
为任何帮助而欢呼。
推荐答案
tile
和重复
是方便的函数,可通过各种方式重复数组:
tile
and repeat
are handy functions when you want to repeat an array in various ways:
In [233]: np.tile(np.array([4,6,6,1]),(3,1))
Out[233]:
array([[4, 6, 6, 1],
[4, 6, 6, 1],
[4, 6, 6, 1]])
在失败时,请注意 fill
的文档:
On the failure, note the docs for fill
:
a.fill(value)
Fill the array with a scalar value.
np.array([4,6,6,1])
不是标量值。 a
初始化为3个元素 float
数组。
np.array([4,6,6,1])
is not a scalar value. a
was initialized as a 3 element float
array.
只要形状正确,就可以为数组的元素分配值:
It is possible to assign values to elements of an array, provided the shapes are right:
In [241]: a=np.empty(3)
In [242]: a[:]=np.array([1,2,3]) # 3 numbers into 3 slots
In [243]: a
Out[243]: array([ 1., 2., 3.])
In [244]: a=np.empty((3,4))
In [245]: a[:]=np.array([1,2,3,4]) # 4 numbers into 4 columns
In [246]: a
Out[246]:
array([[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.]])
此 fill
与对象类型数组一起使用,但结果却大不相同,应谨慎使用:
This fill
works with an object type array, but the result is quite different, and should be used with considerable caution:
In [247]: a=np.empty(3, object)
In [248]: a
Out[248]: array([None, None, None], dtype=object)
In [249]: a.fill(np.array([1,2,3,4]))
In [250]: a
Out[250]: array([array([1, 2, 3, 4]), array([1, 2, 3, 4]), array([1, 2, 3, 4])], dtype=object)
此(3,)数组与其他方法生成的(3,4)数组不同。对象数组的每个元素都是指向同一事物的指针。更改 a
的一个元素中的值会更改所有元素中的值(因为它们是同一对象)。
This (3,) array is not the same as the (3,4) array produced by other methods. Each element of the object array is a pointer to the same thing. Changing a value in one element of a
changes that value in all the elements (because they are the same object).
In [251]: a[0][3]=5
In [252]: a
Out[252]: array([array([1, 2, 3, 5]), array([1, 2, 3, 5]), array([1, 2, 3, 5])], dtype=object)
这篇关于如何用另一个numpy数组填充numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!