【问题标题】:Numpy horizontal concat with failureNumpy 水平连接失败
【发布时间】:2017-03-13 08:40:40
【问题描述】:

我想连接两个形状为(100,3) and (100,7) 的numpy 数组以获得(100,10) 矩阵。

我尝试过使用hstack, concatenate,但只收到ValueError: all the int arrays must have same number of dimensions

在像下面这样的虚拟示例中,它可以工作...

x=np.arange(30).reshape(10,3)
y=np.arange(20).reshape(10,2)
np.concatenate((x,y), axis=1)

更新 1:

我使用 sklearn 的预处理模块(RobustScaler 和 OneHotEncoder)创建了前两个指标。

更新 2:

当使用 scipy.sparse.hstack 时它可以工作,但是为什么

【问题讨论】:

  • 您能否用有关原始阵列的更多信息更新您的问题?
  • 与 hstack 一起使用:np.hstack([x, y])。你确定xy的形状兼容吗?
  • @kennytm,我有 print(x.shape, y.shape) 给出 (100,3) (100,7) 错误消息“所有输入...” - 回溯从堆栈返回 _nx.concatenate(arrs,1)
  • @Roby _nx 是什么? arrs 是什么? np.concatenate((x, y), axis=1) 也适合我。
  • @kennytm 那是 numpy/core/shape_base.py 的回溯——当使用辣味.sparse.hstack 时它可以工作——但为什么?

标签: python arrays numpy concatenation


【解决方案1】:

稀疏 hstack 加入 coo 属性并从中构建一个新的 coo 稀疏矩阵。 numpy hstack 对不同的稀疏结构一无所知。为了进一步解释这一点,我必须解释稀疏构造,并引用各自的函数。

【讨论】:

    【解决方案2】:

    如果你想垂直连接它axis必须等于0。这在the doc for concatenate中有解释。

    在这个链接中我们有这个例子:

    a = np.array([[1, 2], [3, 4]])

    b = np.array([[5, 6]])

    np.concatenate((a, b), axis=0)

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

    np.concatenate((a, b.T), axis=1)

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

    【讨论】:

      【解决方案3】:

      这对我来说非常好:

      import numpy as np
      
      x=np.arange(100 * 3).reshape(100,3)
      y=np.arange(100 * 7).reshape(100,7)
      np.hstack((x,y)).shape  # (100, 10)
      

      【讨论】:

        猜你喜欢
        • 2014-04-19
        • 2016-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-25
        • 1970-01-01
        • 2020-04-30
        • 2017-06-12
        相关资源
        最近更新 更多