numpy按列连接两个维数不同的数组方式

yipeiwu_com6年前Python基础

合并两个维数不同的ndarray

假设我们有一个3×2 numpy数组:

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

现在需要把它与一个一维数组:

y = array(([7, 8,9]))

通过将其添加到行的末尾,连接为一个3×3 numpy数组,如下所示:

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

在numpy中按列连接的方法是:

hstack((x,y))

但是这不行,会报错:

ValueError: arrays must have same number of dimensions

解决方法有两种:

方法一:

>>> x = np.array([[1,2],[3,4],[5,6]])
>>> y = np.array([7,8,9])
>>> np.hstack((x, np.array(([y])).T ))
array([[1, 2, 7],
    [3, 4, 8],
    [5, 6, 9]])

方法二:

>>> x = np.array([[1,2],[3,4],[5,6]])
>>> y = np.array([7,8,9])
>>> np.column_stack((x,y))
array([[1, 2, 7],
    [3, 4, 8],
    [5, 6, 9]])

以上这篇numpy按列连接两个维数不同的数组方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Windows8下安装Python的BeautifulSoup

运行环境:Windows 8.1 Python:2.7.6 在安装的时候,我使用的pip来进行安装,命令如下: 复制代码 代码如下: pip install beautifulsoup4...

如何在mac环境中用python处理protobuf

这篇文章主要介绍了如何在mac环境中用python处理protobuf,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 安装 br...

python conda操作方法

conda 虚拟环境安装 List item conda env list #查看已安装虚拟环境 coda创建虚拟环境非常方便:官方教程:https://conda.io/project...

对numpy数据写入文件的方法讲解

numpy数据保存到文件 Numpy提供了几种数据保存的方法。 以3*4数组a为例: 1. a.tofile("filename.bin") 这种方法只能保存为二进制文件,且不能保存当前...

Python实现求一个集合所有子集的示例

方法一:回归实现 def PowerSetsRecursive(items): """Use recursive call to return all subsets of it...