基本属性

在做一些数据分析的时候,我们通常会把数据存为矩阵的形式,然后python本身对于矩阵的操作是不够的,因此出现了numpy这样一个科学开发库来进行python在次上面的不足。

Numpy's array 类被称为ndarray。 这个对象常用而重要的属性如下:

  • ndarray.ndim: 输出矩阵(数组)的维度
  • ndarray.shape: 输出矩阵的各维数大小,相当于matlab中的size()函数
  • ndarray.size: 输出矩阵(数组)元素的总个数,相当于各维数之积
  • ndarray.dtype: 输出矩阵元素的类型,如int16, int32, float64等
  • ndarray.itemsize: 输出矩阵中每个元素所占字节数

一个例子

>>> from numpy  import *
>>> a = arange(15).reshape(3, 5)
>>> a
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
>>> a.shape
(3, 5)
>>> a.ndim
2
>>> a.dtype.name
'int32'
>>> a.itemsize
4
>>> a.size
15
>>> type(a)
numpy.ndarray
>>> b = array([6, 7, 8])
>>> b
array([6, 7, 8])
>>> type(b)
numpy.ndarray

矩阵创建

python中有多种方式来创建矩阵,第一种是通过Python中的列表直接创建,第二种是通过numpy中的array函数,第三种是利用一些特殊的函数如zerosonesempty等来创建一些特殊的矩阵。

>>> from numpy import *
>>> a = array( [2,3,4] )
>>> a
array([2, 3, 4])
>>> a.dtype
dtype('int32')
>>> b = array([1.2, 3.5, 5.1])
>>> b.dtype
dtype('float64')
-----------------------------------------------
>>> a = array(1,2,3,4) # WRONG
>>> a = array([1,2,3,4]) # RIGHT
-----------------------------------------------
>>> b = array( [ (1.5,2,3), (4,5,6) ] )
>>> b
array([[ 1.5, 2. , 3. ],
[ 4. , 5. , 6. ]])
----------------------------------------------
>>> c = array( [ [1,2], [3,4] ], dtype=complex )
>>> c
array([[ 1.+0.j, 2.+0.j],
[ 3.+0.j, 4.+0.j]])
-----------------------------------------------
>>> zeros( (3,4) )
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
>>> ones( (2,3,4), dtype=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)
>>> empty( (2,3) )
array([[ 3.73603959e-262, 6.02658058e-154, 6.55490914e-260],
[ 5.30498948e-313, 3.14673309e-307, 1.00000000e+000]])

如果想产生一些连续有规则的序列,可以使用numpy中的arange函数,类似于python中的range,功能相当于matlab中的冒号表达式,此外linespace函数产生等分间隔的数。arange函数的形式是arange(start, end, step), 表示从start开始,每隔step取一个数,到end(但不包括end)结束;linespace函数的形式是linespace(start, end, divide),表示将区间[start,end)等分为divide这么多分,并取这些等分的点。

>>> arange( 10, 30, 5 )
array([10, 15, 20, 25])
>>> arange( 0, 2, 0.3 ) # it accepts float arguments
array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])
---------------------------------------------------------------
>>> 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 = linspace( 0, 2*pi, 100 ) # useful to evaluate function at lots of points
>>> f = sin(x)

numpy中常见的其他产生矩阵的函数件这里

常用操作

常见的+,-,*,/,**不再赘述,这里强调一下矩阵的点乘和矩阵的惩罚。

>>> A = array( [[1,1],
... [0,1]] )
>>> B = array( [[2,0],
... [3,4]] )
>>> A*B # elementwise product
array([[2, 0],
[0, 4]])
>>> dot(A,B) # matrix product
array([[5, 4],
[3, 4]])

一些操作符如+=*=只是跟新原数组而不是创造一个新数组,因此如果你在原数组上+=一个新的不同类型的矩阵,得到的矩阵的类型和原矩阵相同。

当不同类型矩阵相操作时,得到的结果倾向于更准确的结果,如整型和浮点型相加,得到结果为浮点型。 
Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class. 
numpy中提供了一些常用的操作,比如矩阵的求和,求矩阵的最大最小值等,如果矩阵有多维,可以通过指定维数来得到某一位的基本操作(先列后行)。

>>> b = arange(12).reshape(3,4)
>>> b
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>>
>>> b.sum(axis=0) # sum of each column
array([12, 15, 18, 21])
>>>
>>> b.min(axis=1) # min of each row
array([0, 4, 8])
>>>
>>> b.cumsum(axis=1) # cumulative sum along each row
array([[ 0, 1, 3, 6],
[ 4, 9, 15, 22],
[ 8, 17, 27, 38]])

常用函数

numpy提供了许多常用的函数,如求平方根,指数等等。

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

更多的函数介绍请点击这里

索引(Indexing), 分片(Slicing), 和迭代(Iterating)

One-dimensional

>>> a = 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

Multidimensional

>>> def f(x,y):
... return 10*x+y
...
>>> b = fromfunction(f,(5,4),dtype=int)
>>> b
array([[ 0, 1, 2, 3],
[10, 11, 12, 13],
[20, 21, 22, 23],
[30, 31, 32, 33],
[40, 41, 42, 43]])
>>> b[2,3]
23
>>> b[0:5, 1] # each row in the second column of b
array([ 1, 11, 21, 31, 41])
>>> b[ : ,1] # equivalent to the previous example
array([ 1, 11, 21, 31, 41])
>>> b[1:3, : ] # each column in the second and third row of b
array([[10, 11, 12, 13],
[20, 21, 22, 23]])

Iterating

>>> for row in b:
... print row
...
[0 1 2 3]
[10 11 12 13]
[20 21 22 23]
[30 31 32 33]
[40 41 42 43]
---------------------------------------------------------
>>> for element in b.flat:
... print element,
...
0 1 2 3 10 11 12 13 20 21 22 23 30 31 32 33 40 41 42 43

Shape Manipulation

改变数组的形状

矩阵各个维数有不同的大小,我们可以通过一些命令如ravel(),resize(),resize()等来改变矩阵的大小,下面是一些例子:

>>> a = floor(10*random.random((3,4)))
>>> a
array([[ 7., 5., 9., 3.],
[ 7., 2., 7., 8.],
[ 6., 8., 3., 2.]])
>>> a.shape
(3, 4)
>>> a.ravel() # flatten the array
array([ 7., 5., 9., 3., 7., 2., 7., 8., 6., 8., 3., 2.])
>>> a.shape = (6, 2)
>>> a.transpose()
array([[ 7., 9., 7., 7., 6., 3.],
[ 5., 3., 2., 8., 8., 2.]])
>>> a
array([[ 7., 5.],
[ 9., 3.],
[ 7., 2.],
[ 7., 8.],
[ 6., 8.],
[ 3., 2.]])
>>> a.resize((2,6))
>>> a
array([[ 7., 5., 9., 3., 7., 2.],
[ 7., 8., 6., 8., 3., 2.]])
>>> a.reshape(3,-1) # 当reshape中的参数为-1时,则对应维度的大小会自动计算
array([[ 7., 5., 9., 3.],
[ 7., 2., 7., 8.],
[ 6., 8., 3., 2.]])

Stacking together different arrays

numpy中提供了一下几种方式来将不同的矩阵压缩在一起:

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

函数column_stackraw_stack可以将一维数组以列(行)的形式插入到二维数组中,其等价于1位数组的vstack

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

Note

在一些复杂的例子中,r_[] 和 c_[] 将数字压缩到数组中非常有用。他们允许使用range literals (":") : 

>>> r_[1:4,0,4]
array([1, 2, 3, 0, 4])

Splitting one array into several smaller ones

Using hsplit, you can split an array along its horizontal axis, either by specifying the number of equally shaped arrays to return, or by specifying the columns after which the division should occur: 
利用hsplitvsplit,可以将矩阵按横坐标和纵坐标进行分割,可以通过指定将数据等分为多少份或者指定分割后所在的列(行)进行分割:

>>> a = floor(10*random.random((2,12)))
>>> a
array([[ 8., 8., 3., 9., 0., 4., 3., 0., 0., 6., 4., 4.],
[ 0., 3., 2., 9., 6., 0., 4., 5., 7., 5., 1., 4.]])
>>> hsplit(a,3) # Split a into 3
[array([[ 8., 8., 3., 9.],
[ 0., 3., 2., 9.]]), array([[ 0., 4., 3., 0.],
[ 6., 0., 4., 5.]]), array([[ 0., 6., 4., 4.],
[ 7., 5., 1., 4.]])]
>>> hsplit(a,(3,4)) # Split a after the third and the fourth column
[array([[ 8., 8., 3.],
[ 0., 3., 2.]]), array([[ 9.],
[ 9.]]), array([[ 0., 4., 3., 0., 0., 6., 4., 4.],
[ 6., 0., 4., 5., 7., 5., 1., 4.]])]

REFER:

https://github.com/wizardforcel/data-science-notebook/blob/master/numpy/NumPy%20%E4%BE%BF%E5%88%A9%E7%9A%84%E5%87%BD%E6%95%B0.md

http://scipy.github.io/old-wiki/pages/Tentative_NumPy_Tutorial#head-1529ae93dd5d431ffe3a1001a4ab1a394e70a5f2

Numpy 常用矩阵计算函数的更多相关文章

  1. numpy 常用工具函数 —— np.bincount/np.average

    numpy 常用工具函数 —— np.bincount/np.average numpy 常用api(一) numpy 常用api(二) 一个函数提供 random_state 的关键字参数(keyw ...

  2. numpy常用函数之randn

    numpy中有一些常用的用来产生随机数的函数,randn就是其中一个,randn函数位于numpy.random中,函数原型如下: numpy.random.randn(d0, d1, ..., dn ...

  3. numpy常用函数学习

    目录numpy常用函数学习点乘法线型预测线性拟合裁剪.压缩和累乘相关性多项式拟合提取符号数组杂项点乘法该方法为数学方法,但是在numpy使用的时候略坑.numpy的点乘为a.dot(b)或numpy. ...

  4. Python数据分析--Numpy常用函数介绍(9)-- 与线性代数有关的模块linalg

    numpy.linalg 模块包含线性代数的函数.使用这个模块,可以计算逆矩阵.求特征值.解线性方程组以及求解行列式等.一.计算逆矩阵 线性代数中,矩阵A与其逆矩阵A ^(-1)相乘后会得到一个单位矩 ...

  5. Numpy常用函数用法大全

    .ndim :维度.shape :各维度的尺度 (2,5).size :元素的个数 10.dtype :元素的类型 dtype(‘int32’).itemsize :每个元素的大小,以字节为单位 ,每 ...

  6. Python数据分析--Numpy常用函数介绍(5)--Numpy中的相关性函数

    摘要:NumPy中包含大量的函数,这些函数的设计初衷是能更方便地使用,掌握解这些函数,可以提升自己的工作效率.这些函数包括数组元素的选取和多项式运算等.下面通过实例进行详细了解. 前述通过对某公司股票 ...

  7. Python数据分析--Numpy常用函数介绍(6)--Numpy中与股票成交量有关的计算

    成交量(volume)是投资中一个非常重要的变量,它是指在某一时段内具体的交易数,可以在分时图中绘制,包括日线图.周线图.月线图甚至是5分钟.30分钟.60分钟图中绘制. 股票市场成交量的变化反映了资 ...

  8. Python常用功能函数

    Python常用功能函数汇总 1.按行写字符串到文件中 import sys, os, time, json def saveContext(filename,*name): format = '^' ...

  9. numpy中argsort函数用法

    在Python中使用help帮助 >>> import numpy >>> help(numpy.argsort) Help on function argsort ...

随机推荐

  1. 07-css的继承性和层叠性

    css有两大特性:继承性和层叠性 继承性 面向对象语言都会存在继承的概念,在面向对象语言中,继承的特点:继承了父类的属性和方法.那么我们现在主要研究css,css就是在设置属性的.不会牵扯到方法的层面 ...

  2. 笔记:IIFE 立即执行的函数表达式 +function ($) { }(window.jQuery);

    在Bootstrap源码(具体请看<Bootstrap源码解析1>)和其他jQuery插件经常看到如下的写法: +function ($) { }(window.jQuery); 这种写法 ...

  3. c需要注意的细节

    1.在纯的.c文件中,例如struct Stu,之后不可以只使用Stu作为关键字来表示这个定义的结构体类型,一定要使用struct Stu一起作为类似int这种关键字来定义或者获取size. 2.函数 ...

  4. eclipse编辑器栏上的路径怎么去掉

    找到这个按钮,点一下就可以了:

  5. ubuntu 开机自启(2B的经历)

    上午写了很细致的开机自启说明文档(需打开terminal进行输出认证).睡了一下午,回来楼主说,联想PM要用Ubuntu Server 当服务器,必须用命令行实现.. 连续各种百度谷歌,看了N多文档, ...

  6. Codeforces822 C. Hacker, pack your bags!

    C. Hacker, pack your bags! time limit per test 2 seconds memory limit per test 256 megabytes input s ...

  7. delphi 过滤开头 结尾 全部 空格的函数

    function TrimAnsi(const S: AnsiString): Ansistring; var I, L: Integer; begin L := Length(S); I := ; ...

  8. Android-WebView加载网页(new WebView(this)方式)

    之前的博客,都是 findViewById(R.id.webview);,来得到WebView, 此博客使用 new WebView(this)方式; AndroidManifest.xml中配置网络 ...

  9. 在.net中使用ETW事件的方法

    直到.net4.5,才有了比较便利的操作ETW的方法. 本文介绍的方法主要来源于Microsoft.Diagnostics.Tracing.TraceEvent官方资料库. 准备 (1)需要用到类:M ...

  10. spark-mllib 密集向量和稀疏向量

    spark-mllib 密集向量和稀疏向量 MLlib支持局部向量和矩阵存储在单台服务器,也支持存储于一个或者多个rdd的分布式矩阵 . 局部向量和局部矩阵是用作公共接口的最简单的数据模型. 基本的线 ...