[英]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)
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) (1) 使用 reshape() 改变一维向量在这里,如果 pointsx 和 pointsy 是一维向量并转置它而不是使用.T (适用于更高维度)
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假设如果 pointsx = [1,2,3,4] 那么 pointsx.reshape(-1,1) 会将其转换为
[[1]
[2]
[3]
[4]
[9]]
(2) Convert 1D vector to matrix and then use transpose. (2) 将一维向量转换为矩阵,然后使用转置。
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)
You are trying to concat a 1D array along its axis 1 (second axis) which is illegal.您正在尝试沿其轴 1(第二轴)连接一维数组,这是非法的。 To fix this you need to reshape it into a 5x1 array and then concat them.
要解决此问题,您需要将其重塑为 5x1 数组,然后将它们连接起来。 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. -1 只是告诉 Numpy 自己计算出该维度的长度,以便解决方案是通用的,并且不仅仅适用于长度为 5 的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.