简体   繁体   English

numpy 用一维数组的值填充 ndarray

[英]numpy fill ndarray with values of a 1D array

I want to fill Ndarray x with values from array b along dimension i without using a for loop.我想用数组 b 沿维度 i 的值填充 Ndarray x ,而不使用 for 循环。 This snippet of code is what I'm currently using but it's not that fast.这段代码是我目前正在使用的,但速度不是那么快。 Is there a better way?有没有更好的办法?

for i in range(len(b)):
    x[...,i,:,:] = b[i]

Edit 1: It's almost what I'm looking for but for higher dimensions it doesn't seem to work.编辑 1:这几乎是我正在寻找的,但对于更高的维度,它似乎不起作用。 x has a dimension of 8 and it's important that the shape of the Ndarray remains the same. x的维度为 8,重要的是 Ndarray 的形状保持不变。 Any more ideas?还有什么想法吗?

import numpy as np

x = np.ones((2,3,4))

b = np.arange(3)

for i in range(len(b)):
    x[:,i,:] = b[i]

x
Out[5]: 
array([[[0., 0., 0., 0.],
        [1., 1., 1., 1.],
        [2., 2., 2., 2.]],

       [[0., 0., 0., 0.],
        [1., 1., 1., 1.],
        [2., 2., 2., 2.]]])

y = np.tile(b,(4,1,2)).T

y
Out[7]: 
array([[[0, 0, 0, 0]],

       [[1, 1, 1, 1]],

       [[2, 2, 2, 2]],

       [[0, 0, 0, 0]],

       [[1, 1, 1, 1]],

       [[2, 2, 2, 2]]])

Edit 2: This seems to do the job编辑2:这似乎可以完成工作

z[...] = b.reshape(1,-1,1)

z
Out[20]: 
array([[[0., 0., 0., 0.],
        [1., 1., 1., 1.],
        [2., 2., 2., 2.]],

       [[0., 0., 0., 0.],
        [1., 1., 1., 1.],
        [2., 2., 2., 2.]]])

Depending on the shape of your destination array you can do something like this根据目标数组的形状,您可以执行以下操作

>>> import numpy as np
>>> x = np.ones((4,8))
>>> x
array([[1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1.]])
>>> b = np.arange(4)
>>> b
array([0, 1, 2, 3])

>>> x[:,1] = b
>>> x
array([[1., 0., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 2., 1., 1., 1., 1., 1., 1.],
       [1., 3., 1., 1., 1., 1., 1., 1.]])

In this example we assigned b to column 1 of the 2D array x在此示例中,我们将b分配给 2D 数组x的第1

If instead you are trying to repeat b a certain number of times you can use np.tile相反,如果您尝试重复b一定次数,则可以使用np.tile

>>> x = np.tile(b, (8,1)).T
>>> x
array([[0, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3, 3, 3, 3]])

There is a faster way.有一种更快的方法。 You can reshape b to add new dimensions and get the advantages of numpy broadcasting rules:您可以重塑 b 以添加新维度并获得 numpy 广播规则的优势:

x[...,:,:,:] = b.reshape(-1,1,1)

Here I am assuming that b is a vector.这里我假设b是一个向量。

Another equivalent way to create new dimensions is as the following code indicates:另一种创建新维度的等效方法如下代码所示:

x[...,:,:,:] = b[:, np.newaxis, np.newaxis]

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

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