numpy.AxisError: axis 1 is out of bounds for array of dimension 1

created at 06-26-2021 views: 303

Error occurs when np.concatenate(,axis=1)

When I want to pile up two one-dimensional data, I

# change
a = [1,2,3]
b = [4,5,6]
# to
[[1,2,3],
[4,5,6]]

Use np.concatenate((a,b),axis=1)

This is because A and B are one-dimensional data, only one dimension, that is, axis = 0, there is no AXIS = 1

I found two solutions

np.vstack((A,B))

You can stack vertical to A and B

print(np.vstack((a,b)))    # Note that the passed parameter is ‘(a,b)’
# [[1 2 3] 
#  [4 5 6]]

The fly in the ointment is that this method can only pass two vectors for stacking:

  • np.newaxis+np.concatenate()

Newaxis, as the name suggests is a new axis, the usage is as follows

a = a[np.newaxis,:]    # Where ‘:’ represents all dimensions (here is 3), the shape of a becomes (1, 3), which is a two-dimensional
# [[1 2 3]]
b = b[np.newaxis,:]
# [[4 5 6]]

At this time, I can pile up 2 (1,3) of the vector (1 * 2, 3) = (2, 3) of the matrix, pay attention to this at this time should use axis = 0, that is, the first Dimension

print(np.concatenate((a,b),axis=0))
# [[1 2 3] 
#  [4 5 6]]
created at:06-26-2021
edited at: 06-26-2021: