简体   繁体   中英

numpy: Append row to a individual 3D array

There's numerous posts and blogs talking about how to manipulate 2D arrays using append, vstack or concatenate, but I couldn't make it work in 3D.

Problem Assumptions:

--The 3D array will have the shape (k, m, 2).

--k will be a known value

--m could range from 1 to n and is not predetermined

In [1]: import numpy as np

In [2]: a = np.empty((3, 1, 2))
Out[2]:
array([[[0., 0.]],
       [[0., 0.]],
       [[0., 0.]]])

In [3]: a[0] = [[5, 6]]

In [4]: a
Out[4]:
array([[[5., 6.]],
       [[0., 0.]],
       [[0., 0.]]])

In [5]: a[0] = np.vstack((a[0], [[10, 15]]))
Out[5]:
ValueError: could not broadcast input array from shape (2,2) into shape(1,2)

In [6]: a[0] = np.append(a[0], [[10, 15]], axis=0)
Out[6]:
ValueError: could not broadcast input array from shape (2,2) into shape(1,2)

The desired output would be.

array([[[5., 6.  ]
        [10., 15.]],
        [[0., 0.]],
        [[0., 0.]]])

Any help would be appreciated.

Clarification:

The output I was looking for would be like this.

[[[ 5,  6],
  [10, 15]],

 [[ 0,  0]],

 [[ 0,  0]]]

Kyle Booth's response gets close with:

c = np.insert(a, 1, b, axis=1)

[[[ 5,  6],
  [10, 15]],

 [[ 0,  0],
  [10, 15]],

 [[ 0,  0],
  [10, 15]]]

This is what you want:

import numpy as np

a = np.array([[[5., 6.]],
       [[0., 0.]],
       [[0., 0.]]])

b = np.array([[10, 15]])

c = np.insert(a,1,b,0)

print c

[[[  5.   6.]]

 [[ 10.  15.]]

 [[  0.   0.]]

 [[  0.   0.]]]

This is not a valid numpy array.

[[[ 5,  6],
  [10, 15]],

 [[ 0,  0]],

 [[ 0,  0]]]

It has 3 'rows', one is (2,2) shape, the others are (1,2).

If I type that in as a list of lists

In [40]: x = np.array([[[5,6],[10,15]],[[0,0]],[[0,0]]])
Out[40]: array([[[5, 6], [10, 15]], [[0, 0]], [[0, 0]]], dtype=object)

I get an array of shape (3,), of dtype object , because it can't create a normal 3d array. And each of those 3 objects are just lists of lists. Wrapping this in np.array doesn't accomplish much.

It might make more sense if I made a list of 3 2d arrays:

In [45]: [np.array(y) for y in x]
Out[45]: 
[array([[ 5,  6],
       [10, 15]]), 
 array([[0, 0]]), 
 array([[0, 0]])
]

The problem isn't with 3D, it's with irregular arrays, arrays of different sizes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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