连接两个numpy数组

时间:2017-03-24 00:29:11

标签: python numpy

我已编写此代码以附加两个numpy数组:

td_XN = searchNegative(X,y,10)
td_XP = searchPosotive(X,y,10)
print(np.array(td_XN).shape, np.array(td_XP).shape)
print(type(td_XN), type(td_XP))
td_X = np.concatenate(td_XP, td_XN)
td_y = [1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0]
print(td_X.shape, len(td_y))

但是,它会产生此错误:

TypeError: only length-1 arrays can be converted to Python scalars

在这一行:

td_X = np.concatenate(td_XP, td_XN)

1 个答案:

答案 0 :(得分:0)

如果你想并排连接(也就是说,创建一个10 -by-2544 * 2的数组):你可以做到

td_X = np.concatenate([td_XP, td_XN],axis=1)

例如

td_X = np.concatenate([[[1,2,3,7],[4,5,6,8]],[[1,2,3],[4,5,6]]],axis=1)

给出

array([[1, 2, 3, 7, 1, 2, 3],
       [4, 5, 6, 8, 4, 5, 6]])

另一方面,如果您想在td_XN以下添加td_XP,您可以

td_X = np.concatenate([td_XP, td_XN],axis=0)

例如,

td_X = np.concatenate([[[1,2,3],[4,5,6]],[[1,2,7],[4,5,8]]],axis=0)

给出

array([[1, 2, 3],
       [4, 5, 6],
       [1, 2, 7],
       [4, 5, 8]])