Reputation: 630
I would like to add another "slice" of data to an existing data cube:
import numpy as np
a = np.array([[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]], [[4, 4, 4, 4], [5, 5, 5, 5], [6, 6, 6, 6]]])
print(a.shape) # (2, 3, 4)
b = np.array([[7, 7, 7], [8, 8, 8]])
print(b.shape) # (2, 3)
c = np.concatenate([a, b], axis=2) # ValueError: all the input arrays must have same number of dimensions
print(c.shape) # wanted result: (2, 3, 5)
So I basically want to add the 2x3 array to the 2x3x4 array by extending the last dimension to 2x3x5. The value error does not quite make sense to me as the array can't be the same shape? What am I doing wrong here?
Upvotes: 1
Views: 4111
Reputation: 221514
Add a new axis at the end for b
and then concatenate -
np.concatenate((a, b[...,None]), axis=2)
So, for the given sample -
In [95]: np.concatenate((a, b[...,None]), axis=2).shape
Out[95]: (2, 3, 5)
Upvotes: 5