Skip to main content
 首页 » 编程设计

python之numpy column_stack (46020, 369) (46020,) (46020,) (46020,)

2024年10月24日7zlslch

我有 4 个具有以下形状的数组:

     X         pred1    pred2   pred3 
(46020, 369) (46020,) (46020,) (46020,) 

我正在尝试将最后 3 列中的列连接到 X 中。 例如,如果我这样做:

array_pack = np.column_stack((X, pred1, pred2, pred3)) 

它给我一个错误:

ValueError: all the input array dimensions except for the concatenation axis must match exactly

我做错了什么? 形状为 (46020,) 的数组应该像 (46020, 1) 吗?

请您参考如下方法:

您可以使用 numpy's atleast_2d() method在 pred1、pred2 和 pred3 上确保数组至少是二维的,即

import numpy as np 
 
X = np.random.rand(46020,369) 
pred1 = np.random.rand(46020) 
pred2 = np.random.rand(46020) 
 
print X.shape,pred1.shape,pred2.shape 

(46020, 369) (46020,) (46020,)

然后,您可以使用 np.vstack 连接数组。

# concatenate 
X_new = np.vstack(np.atleast_2d(X.T,pred1,pred2)).T 
print X_new.shape 

(46020, 371)