简体   繁体   中英

numpy, merge two array of different shape

For two arrays a and b,

a = np.array([[1],[2],[3],[4]])

b = np.array(['a', 'b', 'c', 'd'])

I want to generate the following array

c = np.array([[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd']])

Is there a way to do this efficiently ?

You need:

import numpy as np 

a = np.array([[1],[2],[3],[4]])

b = np.array(['a', 'b', 'c', 'd'])

print(np.array(list(zip(np.concatenate(a), b))))

Output:

[[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd']] 

Alternate Solution

print(np.stack((np.concatenate(a), b), axis=1))

Solution

>>> import numpy as np
>>> a = np.array([[1],[2],[3],[4]])
>>> b = np.array(['a', 'b', 'c', 'd'])


# You have strange array so result is strange
>>> np.array([[a[i],b[i]] for i in range(a.shape[0])])
array([[array([1]), 'a'],
       [array([2]), 'b'],
       [array([3]), 'c'],
       [array([4]), 'd']], dtype=object)



# You want this

>>> np.array([[a[i][0],b[i]] for i in range(a.shape[0])])
array([['1', 'a'],
       ['2', 'b'],
       ['3', 'c'],
       ['4', 'd']], dtype='<U11')
>>>

Note:

You may want to reshape your 'a' array.

>>> a.shape
(4, 1)

>>> a
array([[1],
       [2],
       [3],
       [4]])

Reshape like this for easier use, for next time...

>>> a.reshape(4)
array([1, 2, 3, 4])

你可以做:

c = np.vstack((a.flatten(), b)).T

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