1

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?

piRSquared
  • 285,575
  • 57
  • 475
  • 624
  • 4
    You can't. numpy arrays are *homogeneous*. Each array has **an** element type. – Bakuriu Sep 28 '16 at 18:07
  • 1
    @Bakuriu yes but that type can be a `numpy.object` – Tasos Papastylianou Sep 28 '16 at 18:57
  • 1
    The 'duplicate' describes a different approach - using recarray or structured arrays. The result will be a 1d array with 2 fields, not a 2d array. Which is better depends on what else you need to do with the array. – hpaulj Sep 28 '16 at 19:04

2 Answers2

4

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'>
Tasos Papastylianou
  • 21,371
  • 2
  • 28
  • 57
  • 3
    just to clarify. note that while the individual elements are integers. the column itself would be a numpy object; i.e. if you explicitly wanted a slice to be an array of integers you need to convert the type explicitly at the point of calling, e.g. `np.array(a[:,0], dtype=np.int64)` – Tasos Papastylianou Sep 28 '16 at 18:52
3

A suggested duplicate recommends making a recarray or structured array.

Store different datatypes in one NumPy array?

In this case:

In [324]: a = np.rec.fromarrays((np.arange(2).reshape(-1,1), np.array([['a'],['b']])))
In [325]: a
Out[325]: 
rec.array([[(0, 'a')],
 [(1, 'b')]], 
          dtype=[('f0', '<i4'), ('f1', '<U1')])
In [326]: a['f0']
Out[326]: 
array([[0],
       [1]])
In [327]: a['f1']
Out[327]: 
array([['a'],
       ['b']], 
      dtype='<U1')

(I have reopened this because I think both approaches need to acknowledged. Plus the object answer was already given and accepted.)

Community
  • 1
  • 1
hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Thanks @hpaulj; I confess I neglected to check for duplicates first when I gave my answer; glad it's adding something of benefit though. – Tasos Papastylianou Sep 28 '16 at 19:56
  • It's often easier (and faster) to write an answer than to look for duplicates. But sometimes the sidebar does a good job of finding them. – hpaulj Sep 28 '16 at 20:01