简体   繁体   English

在 np.zeros 或 np.ones 中存储多个 arrays

[英]Storing multiple arrays in a np.zeros or np.ones

I'm trying to initialize a dummy array of length n using np.zeros(n) with dtype=object .我正在尝试使用np.zeros(n)和 dtype dtype=object来初始化长度为n的虚拟数组。 I want to use this dummy array to store n copies of another array of length m .我想使用这个虚拟数组来存储另一个长度为m的数组的n副本。 I'm trying to avoid for loop to set values at each index.我试图避免 for 循环在每个索引处设置值。

I tried using the below code but keep getting error -我尝试使用下面的代码但不断收到错误 -

temp = np.zeros(10, dtype=object)
arr = np.array([1.1,1.2,1.3,1.4,1.5])
res = temp * arr

The desired result should be -期望的结果应该是 -

np.array([[1.1,1.2,1.3,1.4,1.5], [1.1,1.2,1.3,1.4,1.5], ... 10 copies])

I keep getting the error -我不断收到错误 -

operands could not be broadcast together with shapes (10,) (5,) 

I understand that this error arises since the compiler thinks I'm trying to multiply those arrays. So how do I achieve the task?我知道出现此错误是因为编译器认为我正在尝试将这些 arrays 相乘。那么我该如何完成任务呢?

np.tile() is a built-in function that repeats a given array reps times. np.tile()是一个内置的 function,它重复给定的数组重复reps It looks like this is exactly what you need, ie:看起来这正是您所需要的,即:

res = np.tile(arr, 2)
>>> arr = np.array([1.1,1.2,1.3,1.4,1.5])
>>> arr
array([1.1, 1.2, 1.3, 1.4, 1.5])
>>> np.array([arr]*10)

array([[1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM