0

SO I have two arrays

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

That I need to combine such that I get

array([1,'a'],[2,'b'],[3,'c'])

I thought a simple

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

would do it, but it turns everything into a string. How do I avoid that?

array([['1', 'a'],
       ['2', 'b'],
       ['3', 'c']], 
      dtype='<U21')
1
  • You can't all elements of numpy array have to be of same type. Commented Jun 2, 2017 at 1:27

2 Answers 2

2

You can put them in a structured array

In [104]: a=np.array([1,2,3])
     ...: b=np.array(['a','b','c'])

In [105]: arr = np.empty(a.shape[0], dtype='int,U4')
In [106]: arr
Out[106]: 
array([(0, ''), (0, ''), (0, '')], 
      dtype=[('f0', '<i4'), ('f1', '<U4')])
In [107]: arr['f0']=a
In [108]: arr['f1']=b
In [109]: arr
Out[109]: 
array([(1, 'a'), (2, 'b'), (3, 'c')], 
      dtype=[('f0', '<i4'), ('f1', '<U4')])
In [111]: arr['f1']
Out[111]: 
array(['a', 'b', 'c'], 
      dtype='<U4')

https://docs.scipy.org/doc/numpy/user/basics.rec.html

If that isn't useful, stick with separate arrays.

Sign up to request clarification or add additional context in comments.

Comments

1

You can't avoid it, since they need to be of the same type. However, you can do something like this:

import numpy as np

a = np.array([1,2,3])
b = np.array(['a','b','c'])
x = np.stack((a,b),axis=1)

x[0][0].astype(np.int)
>> 1

x[0][1]
>> 'a'

But it's not the nicest code.

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.