热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

常用numpy用法详细介绍

这篇文章介绍常用numpy用法详细介绍

numpy 简介

numpy的存在使得python拥有强大的矩阵计算能力,不亚于matlab。
官方文档(https://docs.scipy.org/doc/numpy-dev/user/quickstart.html)

各种用法介绍

首先是numpy中的数据类型,ndarray类型,和标准库中的array.array并不一样。

ndarray的一些属性

ndarray.ndim
the number of axes (dimensions) of the array. In the Python world, the number of dimensions is referred to as rank.
ndarray.shape
the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the rank, or number of dimensions, ndim.
ndarray.size
the total number of elements of the array. This is equal to the product of the elements of shape.
ndarray.dtype
an object describing the type of the elements in the array. One can create or specify dtype’s using standard Python types. Additionally NumPy provides types of its own. numpy.int32, numpy.int16, and numpy.float64 are some examples.
ndarray.itemsize
the size in bytes of each element of the array. For example, an array of elements of type float64 has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8). It is equivalent to ndarray.dtype.itemsize.
ndarray.data
the buffer containing the actual elements of the array. Normally, we won’t need to use this attribute because we will access the elements in an array using indexing facilities.

ndarray的创建

>>> import numpy as np>>> a = np.array([2,3,4])>>> a
array([2, 3, 4])>>> a.dtype
dtype('int64')>>> b = np.array([1.2, 3.5, 5.1])>>> b.dtype
dtype('float64')

二维的数组

>>> b = np.array([(1.5,2,3), (4,5,6)])>>> b
array([[ 1.5,  2. ,  3. ],
       [ 4. ,  5. ,  6. ]])

创建时指定类型

>>> c = np.array( [ [1,2], [3,4] ], dtype=complex )>>> c
array([[ 1.+0.j,  2.+0.j],
       [ 3.+0.j,  4.+0.j]])

创建一些特殊的矩阵

>>> np.zeros( (3,4) )
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
>>> np.ones( (2,3,4), dtype=np.int16 )                # dtype can also be specified
array([[[ 1, 1, 1, 1],
        [ 1, 1, 1, 1],
        [ 1, 1, 1, 1]],
       [[ 1, 1, 1, 1],
        [ 1, 1, 1, 1],
        [ 1, 1, 1, 1]]], dtype=int16)
>>> np.empty( (2,3) )                                 # uninitialized, output may vary
array([[  3.73603959e-262,   6.02658058e-154,   6.55490914e-260],
       [  5.30498948e-313,   3.14673309e-307,   1.00000000e+000]])

创建一些有特定规律的矩阵

>>> np.arange( 10, 30, 5 )
array([10, 15, 20, 25])
>>> np.arange( 0, 2, 0.3 )                 # it accepts float arguments
array([ 0. ,  0.3,  0.6,  0.9,  1.2,  1.5,  1.8])

>>> from numpy import pi
>>> np.linspace( 0, 2, 9 )                 # 9 numbers from 0 to 2
array([ 0.  ,  0.25,  0.5 ,  0.75,  1.  ,  1.25,  1.5 ,  1.75,  2.  ])
>>> x = np.linspace( 0, 2*pi, 100 )        # useful to evaluate function at lots of points
>>> f = np.sin(x)

一些基本的运算

加减乘除三角函数逻辑运算

>>> a = np.array( [20,30,40,50] )
>>> b = np.arange( 4 )
>>> b
array([0, 1, 2, 3])
>>> c = a-b
>>> c
array([20, 29, 38, 47])
>>> b**2
array([0, 1, 4, 9])
>>> 10*np.sin(a)
array([ 9.12945251, -9.88031624,  7.4511316 , -2.62374854])
>>> a<35
array([ True, True, False, False], dtype=bool)

矩阵运算
matlab中有.* ,./等等
但是在numpy中,如果使用+,-,×,/优先执行的是各个点之间的加减乘除法
如果两个矩阵(方阵)可既以元素之间对于运算,又能执行矩阵运算会优先执行元素之间的运算

>>> import numpy as np>>> A = np.arange(10,20)>>> B = np.arange(20,30)>>> A + B
array([30, 32, 34, 36, 38, 40, 42, 44, 46, 48])>>> A * B
array([200, 231, 264, 299, 336, 375, 416, 459, 504, 551])>>> A / B
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])>>> B / A
array([2, 1, 1, 1, 1, 1, 1, 1, 1, 1])

如果需要执行矩阵运算,一般就是矩阵的乘法运算

>>> A = np.array([1,1,1,1])
>>> B = np.array([2,2,2,2])
>>> A.reshape(2,2)
array([[1, 1],
       [1, 1]])
>>> B.reshape(2,2)
array([[2, 2],
       [2, 2]])
>>> A * B
array([2, 2, 2, 2])
>>> np.dot(A,B)
8
>>> A.dot(B)
8

一些常用的全局函数

>>> B = np.arange(3)
>>> B
array([0, 1, 2])
>>> np.exp(B)
array([ 1.        ,  2.71828183,  7.3890561 ])
>>> np.sqrt(B)
array([ 0.        ,  1.        ,  1.41421356])
>>> C = np.array([2., -1., 4.])
>>> np.add(B, C)
array([ 2.,  0.,  6.])

矩阵的索引分片遍历

>>> a = np.arange(10)**3
>>> a
array([  0,   1,   8,  27,  64, 125, 216, 343, 512, 729])
>>> a[2]
8
>>> a[2:5]
array([ 8, 27, 64])
>>> a[:6:2] = -1000    # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000
>>> a
array([-1000,     1, -1000,    27, -1000,   125,   216,   343,   512,   729])
>>> a[ : :-1]                                 # reversed a
array([  729,   512,   343,   216,   125, -1000,    27, -1000,     1, -1000])
>>> for i in a:
...     print(i**(1/3.))
...
nan
1.0
nan
3.0
nan
5.0
6.0
7.0
8.0
9.0

矩阵的遍历

>>> import numpy as np
>>> b = np.arange(16).reshape(4, 4)
>>> for row in b:
...  print(row)
... 
[0 1 2 3]
[4 5 6 7]
[ 8  9 10 11]
[12 13 14 15]
>>> for node in b.flat:
...  print(node)
... 
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

矩阵的特殊运算

改变矩阵形状--reshape

>>> a = np.floor(10 * np.random.random((3,4)))
>>> a
array([[ 6.,  5.,  1.,  5.],
       [ 5.,  5.,  8.,  9.],
       [ 5.,  5.,  9.,  7.]])
>>> a.ravel()
array([ 6.,  5.,  1.,  5.,  5.,  5.,  8.,  9.,  5.,  5.,  9.,  7.])
>>> a
array([[ 6.,  5.,  1.,  5.],
       [ 5.,  5.,  8.,  9.],
       [ 5.,  5.,  9.,  7.]])

resize和reshape的区别
resize会改变原来的矩阵,reshape并不会

>>> a
array([[ 6.,  5.,  1.,  5.],
       [ 5.,  5.,  8.,  9.],
       [ 5.,  5.,  9.,  7.]])
>>> a.reshape(2,-1)
array([[ 6.,  5.,  1.,  5.,  5.,  5.],
       [ 8.,  9.,  5.,  5.,  9.,  7.]])
>>> a
array([[ 6.,  5.,  1.,  5.],
       [ 5.,  5.,  8.,  9.],
       [ 5.,  5.,  9.,  7.]])
>>> a.resize(2,6)
>>> a
array([[ 6.,  5.,  1.,  5.,  5.,  5.],
       [ 8.,  9.,  5.,  5.,  9.,  7.]])

矩阵的合并

>>> 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.]])

以上就是常用numpy用法详细介绍的详细内容,更多请关注 第一PHP社区 其它相关文章!


推荐阅读
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • 如何实现织梦DedeCms全站伪静态
    本文介绍了如何通过修改织梦DedeCms源代码来实现全站伪静态,以提高管理和SEO效果。全站伪静态可以避免重复URL的问题,同时通过使用mod_rewrite伪静态模块和.htaccess正则表达式,可以更好地适应搜索引擎的需求。文章还提到了一些相关的技术和工具,如Ubuntu、qt编程、tomcat端口、爬虫、php request根目录等。 ... [详细]
  • 本文介绍了在Python3中如何使用选择文件对话框的格式打开和保存图片的方法。通过使用tkinter库中的filedialog模块的asksaveasfilename和askopenfilename函数,可以方便地选择要打开或保存的图片文件,并进行相关操作。具体的代码示例和操作步骤也被提供。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文介绍了Python高级网络编程及TCP/IP协议簇的OSI七层模型。首先简单介绍了七层模型的各层及其封装解封装过程。然后讨论了程序开发中涉及到的网络通信内容,主要包括TCP协议、UDP协议和IPV4协议。最后还介绍了socket编程、聊天socket实现、远程执行命令、上传文件、socketserver及其源码分析等相关内容。 ... [详细]
  • 这是原文链接:sendingformdata许多情况下,我们使用表单发送数据到服务器。服务器处理数据并返回响应给用户。这看起来很简单,但是 ... [详细]
  • 本文介绍了数据库的存储结构及其重要性,强调了关系数据库范例中将逻辑存储与物理存储分开的必要性。通过逻辑结构和物理结构的分离,可以实现对物理存储的重新组织和数据库的迁移,而应用程序不会察觉到任何更改。文章还展示了Oracle数据库的逻辑结构和物理结构,并介绍了表空间的概念和作用。 ... [详细]
  • Java实战之电影在线观看系统的实现
    本文介绍了Java实战之电影在线观看系统的实现过程。首先对项目进行了简述,然后展示了系统的效果图。接着介绍了系统的核心代码,包括后台用户管理控制器、电影管理控制器和前台电影控制器。最后对项目的环境配置和使用的技术进行了说明,包括JSP、Spring、SpringMVC、MyBatis、html、css、JavaScript、JQuery、Ajax、layui和maven等。 ... [详细]
  • 本文是一位90后程序员分享的职业发展经验,从年薪3w到30w的薪资增长过程。文章回顾了自己的青春时光,包括与朋友一起玩DOTA的回忆,并附上了一段纪念DOTA青春的视频链接。作者还提到了一些与程序员相关的名词和团队,如Pis、蛛丝马迹、B神、LGD、EHOME等。通过分享自己的经验,作者希望能够给其他程序员提供一些职业发展的思路和启示。 ... [详细]
  • 目录实现效果:实现环境实现方法一:基本思路主要代码JavaScript代码总结方法二主要代码总结方法三基本思路主要代码JavaScriptHTML总结实 ... [详细]
  • 大连微软技术社区举办《.net core始于足下》活动,获得微软赛百味和易迪斯的赞助
    九月十五日,大连微软技术社区举办了《.net core始于足下》活动,共有51人报名参加,实际到场人数为43人,还有一位专程从北京赶来的同学。活动得到了微软赛百味和易迪斯的赞助,场地也由易迪斯提供。活动中大家积极交流,取得了非常成功的效果。 ... [详细]
  • 本文介绍了九度OnlineJudge中的1002题目“Grading”的解决方法。该题目要求设计一个公平的评分过程,将每个考题分配给3个独立的专家,如果他们的评分不一致,则需要请一位裁判做出最终决定。文章详细描述了评分规则,并给出了解决该问题的程序。 ... [详细]
  • 禁止程序接收鼠标事件的工具_VNC Viewer for Mac(远程桌面工具)免费版
    VNCViewerforMac是一款运行在Mac平台上的远程桌面工具,vncviewermac版可以帮助您使用Mac的键盘和鼠标来控制远程计算机,操作简 ... [详细]
  • 原文地址:https:www.cnblogs.combaoyipSpringBoot_YML.html1.在springboot中,有两种配置文件,一种 ... [详细]
author-avatar
Rony通_184_176
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有