Python:将 kmean.labels_ 添加到 Numpy 数组

Python: append kmean.labels_ to Numpy array

两个Numpy数组的大小分别是:

(406, 278)
(406,)

但是,附加 Numpy 数组时出错:

ValueError: all the input arrays must have same number of dimensions

代码:

y = numpy.array(kmeans.labels_,copy=True)
x = numpy.append(x, y, axis=1); #error
x = numpy.append(x, y, axis=0); #error

如错误所述,您正在尝试将一维数组附加到带有轴参数的二维数组,并且根据文档:

When axis is specified, values must have the correct shape.

您需要先将 y 整形为二维数组:

这两种方法都应该有效:

np.append(x, y[None, :], axis=0)
np.append(x, y.reshape(1,-1), axis=0)

根据 numpy documentation ,

When axis is specified, values must have the correct shape.

所以如果你想把向量y = [0 1 2]附加到矩阵x = [[0, 0],[1, 1],[2, 2]]axis=1,首先你需要把y变成矩阵形式,然后转置它:

x = numpy.zeros((406,278))
y = numpy.zeros((406,))
x = numpy.append(x, numpy.transpose([y]), axis=1);
print(x.shape)   # gives (406,279)