eugene
eugene

Reputation: 41665

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 ?

Upvotes: 1

Views: 1221

Answers (3)

sowlosc
sowlosc

Reputation: 480

You can do:

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

Upvotes: 0

Sociopath
Sociopath

Reputation: 13401

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))

Upvotes: 2

Martin
Martin

Reputation: 3385

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])

Upvotes: 2

Related Questions