Numpy 将二维数组与一维数组连接起来
Numpy concatenate 2D arrays with 1D array
我正在尝试连接 4 个数组,一个一维形状数组 (78427,) 和 3 个二维形状数组 (78427, 375/81/103)。基本上这是 4 个数组,具有 78427 张图像的特征,其中一维数组对于每个图像只有 1 个值。
我尝试按如下方式连接数组:
>>> print X_Cscores.shape
(78427, 375)
>>> print X_Mscores.shape
(78427, 81)
>>> print X_Tscores.shape
(78427, 103)
>>> print X_Yscores.shape
(78427,)
>>> np.concatenate((X_Cscores, X_Mscores, X_Tscores, X_Yscores), axis=1)
这会导致以下错误:
Traceback (most recent call last):
File "", line 1, in
ValueError: all the input arrays must have same number of dimensions
问题似乎是一维数组,但我真的不明白为什么(它也有 78427 个值)。我试图在连接之前转置一维数组,但这也没有用。
如能提供有关连接这些数组的正确方法的任何帮助,我们将不胜感激!
尝试连接 X_Yscores[:, None]
(或 imaluengo 建议的 X_Yscores[:, np.newaxis]
)。这从一维数组创建了一个二维数组。
示例:
A = np.array([1, 2, 3])
print A.shape
print A[:, None].shape
输出:
(3,)
(3,1)
我不确定你是否想要这样的东西:
a = np.array( [ [1,2],[3,4] ] )
b = np.array( [ 5,6 ] )
c = a.ravel()
con = np.concatenate( (c,b ) )
array([1, 2, 3, 4, 5, 6])
或
np.column_stack( (a,b) )
array([[1, 2, 5],
[3, 4, 6]])
np.row_stack( (a,b) )
array([[1, 2],
[3, 4],
[5, 6]])
你可以试试这个单线:
concat = numpy.hstack([a.reshape(dim,-1) for a in [Cscores, Mscores, Tscores, Yscores]])
这里的"secret"是在一个轴上使用已知的公共尺寸进行整形,另一个轴使用-1,它会自动匹配大小(如果需要则创建一个新轴)。
我正在尝试连接 4 个数组,一个一维形状数组 (78427,) 和 3 个二维形状数组 (78427, 375/81/103)。基本上这是 4 个数组,具有 78427 张图像的特征,其中一维数组对于每个图像只有 1 个值。
我尝试按如下方式连接数组:
>>> print X_Cscores.shape
(78427, 375)
>>> print X_Mscores.shape
(78427, 81)
>>> print X_Tscores.shape
(78427, 103)
>>> print X_Yscores.shape
(78427,)
>>> np.concatenate((X_Cscores, X_Mscores, X_Tscores, X_Yscores), axis=1)
这会导致以下错误:
Traceback (most recent call last): File "", line 1, in ValueError: all the input arrays must have same number of dimensions
问题似乎是一维数组,但我真的不明白为什么(它也有 78427 个值)。我试图在连接之前转置一维数组,但这也没有用。
如能提供有关连接这些数组的正确方法的任何帮助,我们将不胜感激!
尝试连接 X_Yscores[:, None]
(或 imaluengo 建议的 X_Yscores[:, np.newaxis]
)。这从一维数组创建了一个二维数组。
示例:
A = np.array([1, 2, 3])
print A.shape
print A[:, None].shape
输出:
(3,)
(3,1)
我不确定你是否想要这样的东西:
a = np.array( [ [1,2],[3,4] ] )
b = np.array( [ 5,6 ] )
c = a.ravel()
con = np.concatenate( (c,b ) )
array([1, 2, 3, 4, 5, 6])
或
np.column_stack( (a,b) )
array([[1, 2, 5],
[3, 4, 6]])
np.row_stack( (a,b) )
array([[1, 2],
[3, 4],
[5, 6]])
你可以试试这个单线:
concat = numpy.hstack([a.reshape(dim,-1) for a in [Cscores, Mscores, Tscores, Yscores]])
这里的"secret"是在一个轴上使用已知的公共尺寸进行整形,另一个轴使用-1,它会自动匹配大小(如果需要则创建一个新轴)。