jonem
jonem

Reputation: 459

Numpy concatenate giving error: axis 1 is out of bounds for array of dimension 1

The dimensions seem to work out, but it's still complaining (blood pressure building):

x = np.array([1,2,3,4])
y = np.array([5,6,7,8])
m = np.array([9,10])
pointsx = np.concatenate((x,[m[0]]), axis=0)
pointsy = np.concatenate((y,[m[1]]), axis=0)
points = np.concatenate((pointsx.T,pointsy.T), axis=1)

Upvotes: 3

Views: 9960

Answers (2)

Hetal Thaker
Hetal Thaker

Reputation: 717

There may be two solutions as :

(1) use reshape() to change 1D Vector Here in case pointsx and pointsy are 1D Vector and to transpose it rather than using .T (which works for higher dimensions)

import numpy as np
x = np.array([1,2,3,4])
y = np.array([5,6,7,8])
m = np.array([9,10])
pointsx = np.concatenate((x,[m[0]]), axis=0)
pointsy = np.concatenate((y,[m[1]]), axis=0)

points = np.concatenate((pointsx.reshape(-1,1),pointsy.reshape(-1,1)), axis=1)
print(points)

Suppose if pointsx = [1,2,3,4] then pointsx.reshape(-1,1) will convert it to

[[1]
 [2]
 [3]
 [4]
 [9]]

(2) Convert 1D vector to matrix and then use transpose.

import numpy as np
x = np.array([1,2,3,4])
y = np.array([5,6,7,8])
m = np.array([9,10])
pointsx = np.concatenate((x,[m[0]]), axis=0)
pointsy = np.concatenate((y,[m[1]]), axis=0)

points = np.concatenate((np.matrix(pointsx).T,np.matrix(pointsy).T), axis=1)
print(points)

Upvotes: 4

EnderShadow8
EnderShadow8

Reputation: 1040

You are trying to concat a 1D array along its axis 1 (second axis) which is illegal. To fix this you need to reshape it into a 5x1 array and then concat them. Like so:

x = np.array([1,2,3,4])
y = np.array([5,6,7,8])
m = np.array([9,10])
pointsx = np.concatenate((x,[m[0]]), axis=0)
pointsy = np.concatenate((y,[m[1]]), axis=0)
pointsx = pointsx.reshape((-1, 1))
pointsy = pointsy.reshape((-1, 1))
points = np.concatenate((pointsx, pointsy), axis=1)

The -1 simply tells Numpy to work out the length of that dimension by itself so that the solution is general and doesn't just apply to an array of length 5.

Upvotes: 0

Related Questions