使用np.concatenate时的维度问题

时间:2016-05-04 05:12:00

标签: python python-2.7 numpy

我有一个np.array user_matrix和另一个列表user_clust。我想将user_clust连接到user_matrix的最后一列。以下是我的代码。

np.concatenate( (user_matrix, user_clust), 1)

但是我收到了这个错误:

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

两个数据集的维度:

user_matrix.shape #(10000, 110)
user_clust.shape  #(10000,)

据我所知,user_clust是1维的,不像user_matrix是二维的,但不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:1)

您似乎有一个二维数组,并且您想在最后添加一个向量作为新列:

>>> import numpy as np
>>> mat = np.arange(12).reshape(3,4)
>>> mat
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> vct = np.arange(100, 103)
>>> vct
array([100, 101, 102])
>>> np.concatenate((mat, vct.reshape(vct.shape + (1,))), axis=1)
array([[  0,   1,   2,   3, 100],
       [  4,   5,   6,   7, 101],
       [  8,   9,  10,  11, 102]])

另一种选择是使用np.append

>>> np.append(mat, vct.reshape(vct.shape + (1,)), axis=1)
array([[  0,   1,   2,   3, 100],
       [  4,   5,   6,   7, 101],
       [  8,   9,  10,  11, 102]])

另一个选项是np.hstack

>>> np.hstack( (mat, vct.reshape(vct.shape + (1,))) )
array([[  0,   1,   2,   3, 100],
       [  4,   5,   6,   7, 101],
       [  8,   9,  10,  11, 102]])

诀窍

在所有情况下,都需要将矢量vct重新整形为列矢量:

>>> vct
array([100, 101, 102])
>>> vct.reshape(vct.shape + (1,))
array([[100],
       [101],
       [102]])

替代

根据hpaulj在评论中的建议,将vct转换为列向量的另一种方法是使用以下格式:

>>> vct[..., None]
array([[100],
       [101],
       [102]])
>>> np.concatenate((mat, vct[..., None]), axis=1)
array([[  0,   1,   2,   3, 100],
       [  4,   5,   6,   7, 101],
       [  8,   9,  10,  11, 102]])