简体   繁体   English

将一个 numpy 数组的值添加到特定索引处的 2D numpy 数组的最快方法

[英]Fastest way to add values of one numpy array to a 2D numpy array at particular index

I have a 2D numpy array of zeros, a list of numpy arrays (which can be of different lengths) and a list of indices.我有一个 2D numpy 零数组、一个 numpy 数组列表(可以是不同的长度)和一个索引列表。 I want to add the contents of each of the arrays in the list from the start of the corresponding row indice in the 2D array.我想从二维数组中相应行索引的开头添加列表中每个数组的内容。

Of course, I can just loop over the arrays.当然,我可以循环遍历数组。 However, I need to perform this operations for many different samples.但是,我需要对许多不同的样本执行此操作。 Therefore, I was wondering whether anybody is aware of a more efficient way to do this.因此,我想知道是否有人知道一种更有效的方法来做到这一点。

In [1]: A = np.zeros((5, 5))
   ...: arrays = [np.random.randint(1, 10, size=(1,5)) for i in range(3)]
   ...: indices = [1, 3, 4]
   ...: print(arrays)
Out[1]:
[array([3, 1, 3, 6]), array([4, 9]), array([5, 9, 6])]

Expected output:预期输出:

array([[0., 0., 0., 0., 0.], 
       [3., 1., 3., 6., 0.], 
       [0., 0., 0., 0., 0.], 
       [4., 9., 0., 0., 0.], 
       [5., 9., 6., 0., 0.]] 

Any help would be much appreciated!任何帮助将非常感激!

Using zip :使用zip

for i, a in zip(indices, arrays):
    A[i, :len(a)] = a

Output:输出:

array([[0., 0., 0., 0., 0.],
       [3., 1., 3., 6., 0.],
       [0., 0., 0., 0., 0.],
       [4., 9., 0., 0., 0.],
       [5., 9., 6., 0., 0.]])

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

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