Python numpy实现数组合并实例(vstack,hstack)

yipeiwu_com7年前Python基础

若干个数组可以沿不同的轴合合并到一起,vstack,hstack的简单用法,

>>> a = np.floor(10*np.random.random((2,2)))
>>> a
array([[ 8., 8.],
    [ 0., 0.]])
>>> b = np.floor(10*np.random.random((2,2)))
>>> b
array([[ 1., 8.],
    [ 0., 4.]])
>>> np.vstack((a,b))
array([[ 8., 8.],
    [ 0., 0.],
    [ 1., 8.],
    [ 0., 4.]])
>>> np.hstack((a,b))
array([[ 8., 8., 1., 8.],
    [ 0., 0., 0., 4.]])

column_stack函数功能是将一个1D数组转化成一个2D数组,相当于将1D数组垂直排列。

>>> from numpy import newaxis
>>> np.column_stack((a,b))  # With 2D arrays
array([[ 8., 8., 1., 8.],
    [ 0., 0., 0., 4.]])
>>> a = np.array([4.,2.])
>>> b = np.array([2.,8.])
>>> a[:,newaxis] # This allows to have a 2D columns vector
array([[ 4.],
    [ 2.]])
>>> np.column_stack((a[:,newaxis],b[:,newaxis]))
array([[ 4., 2.],
    [ 2., 8.]])
>>> np.vstack((a[:,newaxis],b[:,newaxis])) # The behavior of vstack is different
array([[ 4.],
    [ 2.],
    [ 2.],
    [ 8.]])

对于多维数组,hstack沿第二轴,vstack沿第一条轴。

总结

以上就是本文关于Python numpy实现数组合并实例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

django中forms组件的使用与注意

forms组件 django框架提供了一个Form类,来进行web开发中的表单提交数据的处理工作。 导入相关模块 from django import forms from dja...

Python 内置变量和函数的查看及说明介绍

Python 内置变量和函数的查看及说明介绍

Python 解释器内置了一些常量和函数,叫做内置常量(Built-in Constants)和内置函数(Built-in Functions),我们怎么在 查看全部内置常量和函数的名字...

python按行读取文件并找出其中指定字符串

python按行读取文件并找出其中指定字符串 #coding=utf-8 import os, time, sys, re #reload(sys) #sys.setdefaul...

python与mysql数据库交互的实现

python与mysql数据库交互的实现

1、安装pymysql库 如果你想要使用python操作MySQL数据库,就必须先要安装pymysql库,这个库的安装很简单,直接使用pip install pymysql;进行安装。...

python itchat给指定联系人发消息的方法

itchat模块 官方参考文档:https://itchat.readthedocs.io/zh/latest/ 安装 pip install itchat / pip3 insta...