0

Currently I have two arrays: the shape of a1 is (5,4,6,3), the second one a2 is (5,4,6) and finally I want to get a merged array (5,4,6,4)

Currently I "for-loop" each (6,3) array and np.stack it with corresponding (6,1) to (6,4).

for i in range(a1.shape[0]):
    for j in range(a1.shape[1]):
        a = np.hstack((a1[i,j], a2[i,j].reshape(6,1)))

However, it's not pretty efficient if it's much bigger than 5*4.

Do you have a better way?

1 Answers1

0

Is this what you want?

import numpy as np

a1 = np.ones((5, 4, 6, 3))
a2 = np.ones((5, 4, 6))

result = np.concatenate((a1, a2[..., np.newaxis]), axis=-1)

print(result.shape)

(5, 4, 6, 4)
iz_
  • 15,923
  • 3
  • 25
  • 40
  • Just to add: An alternative is to use `np.reshape` or `np.expand_dims` to bring the second array to the same shape as the first. – crazyGamer Jan 24 '19 at 05:00
  • I got the result I want. It's fantastic! So you just expand the dimension to (5,4,6,1) and the problem is solved............ Cool. – Michael Sun Jan 24 '19 at 05:10
  • What about the pinv? – Michael Sun Jan 24 '19 at 05:10
  • @MichaelSun Please avoid asking multiple distinct questions in only one question. Create another question. See https://meta.stackoverflow.com/q/371614. Also, see https://stackoverflow.com/help/someone-answers – iz_ Jan 24 '19 at 05:15
  • Oh, thanks for your mention. I will create another question. – Michael Sun Jan 24 '19 at 05:22