1

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 ?

3 Answers 3

2

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))
Sign up to request clarification or add additional context in comments.

1 Comment

oh.. then would ` list(zip(np.concatenate(a), b)` be better? np.array(zip(np.concatenate(a), b)) returns weird object..
2

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

Comments

0

You can do:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.