piRSquared piRSquared - 2 months ago 22
Python Question

concatenate arrays with mixed types

consider the

np.array
a


a = np.concatenate(
[np.arange(2).reshape(-1, 1),
np.array([['a'], ['b']])],
axis=1)
a

array([['0', 'a'],
['1', 'b']],
dtype='|S11')


How can I execute this concatenation such that the first column of
a
remains integers?

Answer

You can mix types in a numpy array by using a numpy.object as the dtype:

>>> import numpy as np
>>> a = np.empty((2, 0), dtype=np.object)
>>> a = np.append(a, np.arange(2).reshape(-1,1), axis=1)
>>> a = np.append(a, np.array([['a'],['b']]), axis=1)

>>> a
array([[0, 'a'],
       [1, 'b']], dtype=object)

>>> type(a[0,0])
<type 'int'>

>>> type(a[0,1])
<type 'str'>
Comments