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

yipeiwu_com5年前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生成矩阵、串联矩阵代码分享的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

python的移位操作实现详解

因为要将js的一个签名算法移植到python上,遇到一些麻烦。 int无限宽度,不会溢出 算法中需要用到了32位int的溢出来参与运算,但是python的int是不会溢出的,达到界限后...

tornado框架blog模块分析与使用

复制代码 代码如下:#!/usr/bin/env python## Copyright 2009 Facebook## Licensed under the Apache License...

Python中列表、字典、元组数据结构的简单学习笔记

列表 列表是Python中最具灵活性的有序集合对象类型。与字符串不同的是,列表可以包含任何类型的对象:数字、字符串甚至其他列表。列表是可变对象,它支持原地修改的操作。 Python的列表...

python动态监控日志内容的示例

日志文件一般是按天产生,则通过在程序中判断文件的产生日期与当前时间,更换监控的日志文件程序只是简单的示例一下,监控test1.log 10秒,转向监控test2.log 程序监控使用是l...

Django中Forms的使用代码解析

Django中Forms的使用代码解析

本文研究的主要是Django中Forms的使用,具体如下。 创建文件do.html {% extends 'base.html' %} {% block mainbody %}...