简体   繁体   English

将行向量添加到 3-D numpy 数组

[英]Adding a row vector to a 3-D numpy array

Suppose I have a 3-D array in numpy假设我在 numpy 中有一个 3-D 数组

a = [ [[1,2], [3,4]] , [[5,6], [7,8]] ]

I want to add a new row vector to a matrix so that the output would be for example, if I wanted to add the row vector [9,10] to the second matrix in the 3d array:我想向矩阵添加一个新的行向量,以便输出例如,如果我想将行向量 [9,10] 添加到 3d 数组中的第二个矩阵:

a = [ [[1,2], [3,4]] , [[5,6], [7,8], [9,10]] ]

I know how to add row vectors to 2-D arrays using np.append .我知道如何使用np.append将行向量添加到二维数组。 But I don't know how to do it with 3-D arrays.但我不知道如何用 3-D 数组来做到这一点。 I have tried to use np.append but all I get are either dimension errors, flattened arrays or just the wrong array.我曾尝试使用np.append但我得到的只是维度错误、扁平数组或只是错误的数组。 What would be the correct way to do this in numpy?在 numpy 中执行此操作的正确方法是什么?

Numpy does memory optimization and creates np.ndarray of the size that you requested. Numpy 进行内存优化并创建您请求的大小的np.ndarray It's better that you create an array of the size that you need at once and manipulate it instead of adding new rows many times.最好一次创建一个您需要的大小的数组并对其进行操作,而不是多次添加新行。

So, if you will use many appends: use list.因此,如果您将使用许多附加:使用列表。 If you know the total size: use numpy array.如果您知道总大小:使用 numpy 数组。

Another problem that you face is: The shape is not uniform.您面临的另一个问题是:形状不统一。 That is那是

a = np.array([ [[1,2], [3,4]] , [[5,6], [7,8]] ])
# a.shape is (2, 2, 2)
new_a = np.array([ [[1,2], [3,4]] , [[5,6], [7,8], [9, 10] ]])
# What is the shape of new_a?

A code that does what you want is:可以执行您想要的操作的代码是:

import numpy as np
a = np.array([ [[1,2], [3,4]] , [[5,6], [7,8]] ])
b = np.array([9,10])


res = np.zeros(a.shape[0], dtype="object")
res[0] = a[0]
res[1] = np.zeros((a.shape[1]+1, a.shape[2]))
res[1, :-1] = a[1, :]
res[1, -1] = b

You can achieve you goal like as follows, but the question remains in how far this is sensible because vectorization with an array that has dtype=object becomes more difficult.您可以实现如下目标,但问题仍然是这在多大程度上是明智的,因为使用具有dtype=object的数组进行矢量化变得更加困难。 But here you go:但是你去吧:

import numpy as np
a = np.array([ [[1,2], [3,4]] , [[5,6], [7,8]] ])
b = np.array([9,10])

res = np.array([a[0],np.vstack([a[1],b])],dtype=object)

Output:输出:

array([array([[1, 2],
              [3, 4]]), array([[ 5,  6],
                               [ 7,  8],
                               [ 9, 10]])], dtype=object)

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

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