Python numpy生成矩阵、串联矩阵代码分享

yipeiwu_com6年前Python基础

import numpy

生成numpy矩阵的几个相关函数:

numpy.array()
numpy.zeros()
numpy.ones()
numpy.eye()

串联生成numpy矩阵的几个相关函数:

numpy.array()
numpy.row_stack()
numpy.column_stack()
numpy.reshape()

>>> import numpy 
>>> numpy.eye(3) 
array([[ 1., 0., 0.], 
    [ 0., 1., 0.], 
    [ 0., 0., 1.]]) 
>>> numpy.zeros(3) 
array([ 0., 0., 0.]) 
>>> numpy.ones(3) 
array([ 1., 1., 1.]) 
>>> x1 = numpy.array((1, 2, 3)) 
>>> x1 
array([1, 2, 3]) 
>>> x2 = numpy.array([4, 5, 6]) 
>>> x2 
array([4, 5, 6]) 
>>> x3 = numpy.array((x1, x2)) 
>>> x3 
array([[1, 2, 3], 
    [4, 5, 6]]) 
>>> x4 = x3.reshape(2, 3) 
>>> x4 
array([[1, 2, 3], 
    [4, 5, 6]]) 
>>> x4 = x3.reshape(3, 2) 
>>> x4 
array([[1, 2], 
    [3, 4], 
    [5, 6]]) 
>>> x5 = numpy.row_stack(x1, x2) 
Traceback (most recent call last): 
 File "<stdin>", line 1, in <module> 
TypeError: vstack() takes exactly 1 argument (2 given) 
>>> x5 = numpy.row_stack((x1, x2)) 
>>> x5 
array([[1, 2, 3], 
    [4, 5, 6]]) 
>>> x6 = numpy.row_stack([x1, x2]) 
>>> x6 
array([[1, 2, 3], 
    [4, 5, 6]]) 
>>> x7 = numpy.row_stack((x6, x2)) 
>>> x7 
array([[1, 2, 3], 
    [4, 5, 6], 
    [4, 5, 6]]) 
>>> x7[0] 
array([1, 2, 3]) 
>>> x7[1] 
array([4, 5, 6]) 
>>> x7[2] 
array([4, 5, 6]) 
>>> x8 = numpy.column_stack([x1, x2, x1, x2]) 
>>> x8 
array([[1, 4, 1, 4], 
    [2, 5, 2, 5], 
    [3, 6, 3, 6]]) 
>>> x8[0] 
array([1, 4, 1, 4]) 
>>> x8[1] 
array([2, 5, 2, 5]) 
>>> x8[2] 
array([3, 6, 3, 6]) 
>>> x8[3] 
Traceback (most recent call last): 
 File "<stdin>", line 1, in <module> 
IndexError: index 3 is out of bounds for axis 0 with size 3 
>>> x8[0][3] 
4 
>>> 

python生成1行四列全2矩阵

print np.ones((1,4))*2

总结

以上就是本文关于Python numpy生成矩阵、串联矩阵代码分享的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

Flask解决跨域的问题示例代码

Flask解决跨域的问题示例代码

跨域文件上传的时候,浏览器会自动发起一个 OPTIONS 方法到服务器,现在后台解决前端跨域解决前端跨域请求的问题 客户端发起的这个 OPTIONS 可以说是一个“预请求”,用于探测后续...

django中使用事务及接入支付宝支付功能

django中使用事务及接入支付宝支付功能

之前一直想记录一下在项目中使用到的事务以及支付宝支付功能,自己一直犯懒没有完,趁今天有点兴致,在这记录一下。 商城项目必备的就是支付订单的功能,所以就会涉及到订单的保存以及支付接口的引入...

pandas实现选取特定索引的行

如下所示: >>> import numpy as np >>> import pandas as pd >>> index=n...

Python中使用Beautiful Soup库的超详细教程

Python中使用Beautiful Soup库的超详细教程

1. Beautiful Soup的简介 简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。官方解释如下:    ...

python 抓包保存为pcap文件并解析的实例

首先是抓包,使用scapy模块, sniff()函数 在其中参数为本地文件路径时,操作为打开本地文件 若参数为BPF过滤规则和回调函数,则进行Sniff,回调函数用于对Sniff到的数据...