python - 将 hstack 应用于矩阵数组

标签 python numpy

给定一个矩阵数组matrices_w,我想在每个矩阵上应用np.hstack函数:

matrices_w = np.asarray([[[1,2,3],[4,5,6]],[[9,8,7],[6,5,4]]])
array([[[1, 2, 3],
        [4, 5, 6]],

       [[9, 8, 7],
        [6, 5, 4]]])

这样就可以得到所需的结果:

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

到目前为止,我已经尝试了多种功能,包括 np.apply_along_axis 但无法正常工作。

最佳答案

在这种情况下,reshape 是最简单、最快的方法。但弄清楚为什么 hstack 不起作用可能是值得的。

In [192]: arr = np.array([[[1,2,3],[4,5,6]],[[9,8,7],[6,5,4]]])              

hstack 运行,但产生不同的顺序:

In [193]: np.hstack(arr)                                                     
Out[193]: 
array([[1, 2, 3, 9, 8, 7],
       [4, 5, 6, 6, 5, 4]])

这是因为 hstack 将数组的第一个维度视为列表,并将两个数组连接起来:

In [194]: np.concatenate([arr[0],arr[1]], axis=-1)                           
Out[194]: 
array([[1, 2, 3, 9, 8, 7],
       [4, 5, 6, 6, 5, 4]])

如果我们将其拆分为第二维上的列表,我们将得到您想要的顺序:

In [195]: np.concatenate([arr[:,0],arr[:,1]], axis=-1)                       
Out[195]: 
array([[1, 2, 3, 4, 5, 6],
       [9, 8, 7, 6, 5, 4]])

关于python - 将 hstack 应用于矩阵数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56209401/

相关文章:

python - Python 中的分箱频率分布

python - 字符串索引超出范围? - Python

python - 在 Google Colab 中运行 conda 环境

python-3.x - 将日期时间转换为没有时区信息的numpy日期时间

linux - 即使安装后也没有名为 numpy 的模块

python - 合并数组和绘图

python - GUI 和功能的应用程序结构

python - 光束 : ReadAllFromText receive string or list from DoFn different behavior?

python - 将 unicode 元素读入 numpy 数组

python - 如何在 python 中模拟 biased die?