简体   繁体   中英

combine numpy array “element-wise”

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?

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)

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