L. Joe
L. Joe

Reputation: 45

Concatenating two numpy array issues

I have two numpy arrays of shape

(129873, 12)
(129873,)

I would like to concatenate these so they are in the shape of:

(129873, 13)

I have tried numpy.concatenate and numpy.vstack but seem to be getting errors:

ValueError: all the input arrays must have same number of dimensions

Any suggestions on how to do this?

Upvotes: 2

Views: 103

Answers (2)

Ohumeronen
Ohumeronen

Reputation: 2086

I think this was already answered here:

Numpy: Concatenating multidimensional and unidimensional arrays

import numpy
a = numpy.array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]])
b = numpy.array([5, 6, 6])
c = numpy.column_stack((a,b))
print a
print b
print c
print a.shape
print b.shape
print c.shape

This gives you:

[[1 2 3 4 5]
 [1 2 3 4 5]
 [1 2 3 4 5]]
[5 6 6]
[[1 2 3 4 5 5]
 [1 2 3 4 5 6]
 [1 2 3 4 5 6]]
(3, 5)
(3,)
(3, 6)

Upvotes: 2

hpaulj
hpaulj

Reputation: 231738

So one array has 2 dimensions, the other 1:

(129873, 12)
(129873,)

You need to change the 2nd to have shape (129873,1). Then you can concatenate on axis 1.

There are a number of way of do this. The [:,None] or np.newaxis indexing is my favorite:

In [648]: A=np.ones((3,4),int)

In [649]: B=np.ones((3,),int)

In [650]: B[:,None].shape
Out[650]: (3, 1)

In [651]: np.concatenate((A,B[:,None]),axis=1).shape
Out[651]: (3, 5)

B.reshape(-1,1) also works. Also np.atleast_2d(B).T and np.expand_dims(B,1).

np.column_stack((A,B)) uses np.array(arr, copy=False, subok=True, ndmin=2).T to ensure each array has the right number of dimensions.

While there are friendly covers to concatenate like column_stack, it's important to know how to change dimensions directly.

Upvotes: 1

Related Questions