我一直在尝试用np.concatenate连接两个一维数组,但它不能像预期的那样工作。有没有人能告诉我哪里弄错了?
我的代码如下:
x = np.array([1.13793103, 0.24137931, 0.48275862, 1.24137931, 1.00000000, 1.89655172])
y = np.array([0.03666667, 0.00888889, 0.01555556, 0.04      , 0.03222222, 0.06111111])
z = np.concatenate((x,y), axis=0)
print(z)
array([1.13793103, 0.24137931, 0.48275862, ... 0.04, 0.03222222, 0.06111111])
print(f'{type(x)} {type(y)} {type(z)}')
<class 'numpy.ndarray'> <class 'numpy.ndarray'> <class 'numpy.ndarray'>
print(f'{x.shape} {y.shape} {z.shape}')
(6,) (6,) (12,)所以,不是将y作为新的数组添加,而是将两个数组连接起来,这不是我的本意。我正在寻找的东西如下:
array([1.13793103, 0.24137931, 0.48275862, 1.24137931, 1.00000000, 1.89655172],
      [0.03666667, 0.00888889, 0.01555556, 0.04      , 0.03222222, 0.06111111])发布于 2020-05-06 05:52:08
如果要连接的数组中存在该维度,则可以使用np.concatenate沿某个轴进行连接:
x = np.array([1,2,3])
y = np.array([4,5,6])这里,x和y有形状(3,),所以只有一个轴。这意味着您只能沿着该轴(即axis=0)进行连接:
z = np.concatenate((x,y))
z.shape
out : (6,)沿着axis=1连接将抛出一个错误:
z = np.concatenate((x,y), axis=1)
AxisError: axis 1 is out of bounds for array of dimension 1如果对x和y进行重塑,则可以使np.concatenate工作:
x, y = x.reshape(-1,1), y.reshape(-1,1)现在,两者都具有形状(3,1),并且可以沿轴1连接:
z = np.concatenate((x.reshape(-1,1),y.reshape(-1,1)),axis=1)
z.shape
(6,2)或者,可以重塑为(1,3)并沿轴0连接:
z = np.concatenate((x.reshape(1,-1),y.reshape(1,-1)),axis=0)
z.shape
(2,6)或者使用np.vstack,它不需要重新整形。
https://stackoverflow.com/questions/61623257
复制相似问题