[关闭]
@chanvee 2015-04-27T07:38:06.000000Z 字数 6396 阅读 21836

python numpy笔记

Python numpy


基本属性


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

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

一个例子


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

矩阵创建


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

  1. >>> from numpy import *
  2. >>> a = array( [2,3,4] )
  3. >>> a
  4. array([2, 3, 4])
  5. >>> a.dtype
  6. dtype('int32')
  7. >>> b = array([1.2, 3.5, 5.1])
  8. >>> b.dtype
  9. dtype('float64')
  10. -----------------------------------------------
  11. >>> a = array(1,2,3,4) # WRONG
  12. >>> a = array([1,2,3,4]) # RIGHT
  13. -----------------------------------------------
  14. >>> b = array( [ (1.5,2,3), (4,5,6) ] )
  15. >>> b
  16. array([[ 1.5, 2. , 3. ],
  17. [ 4. , 5. , 6. ]])
  18. ----------------------------------------------
  19. >>> c = array( [ [1,2], [3,4] ], dtype=complex )
  20. >>> c
  21. array([[ 1.+0.j, 2.+0.j],
  22. [ 3.+0.j, 4.+0.j]])
  23. -----------------------------------------------
  24. >>> zeros( (3,4) )
  25. array([[0., 0., 0., 0.],
  26. [0., 0., 0., 0.],
  27. [0., 0., 0., 0.]])
  28. >>> ones( (2,3,4), dtype=int16 ) # dtype can also be specified
  29. array([[[ 1, 1, 1, 1],
  30. [ 1, 1, 1, 1],
  31. [ 1, 1, 1, 1]],
  32. [[ 1, 1, 1, 1],
  33. [ 1, 1, 1, 1],
  34. [ 1, 1, 1, 1]]], dtype=int16)
  35. >>> empty( (2,3) )
  36. array([[ 3.73603959e-262, 6.02658058e-154, 6.55490914e-260],
  37. [ 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这么多分,并取这些等分的点。

  1. >>> arange( 10, 30, 5 )
  2. array([10, 15, 20, 25])
  3. >>> arange( 0, 2, 0.3 ) # it accepts float arguments
  4. array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])
  5. ---------------------------------------------------------------
  6. >>> linspace( 0, 2, 9 ) # 9 numbers from 0 to 2
  7. array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])
  8. >>> x = linspace( 0, 2*pi, 100 ) # useful to evaluate function at lots of points
  9. >>> f = sin(x)

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

常用操作


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

  1. >>> A = array( [[1,1],
  2. ... [0,1]] )
  3. >>> B = array( [[2,0],
  4. ... [3,4]] )
  5. >>> A*B # elementwise product
  6. array([[2, 0],
  7. [0, 4]])
  8. >>> dot(A,B) # matrix product
  9. array([[5, 4],
  10. [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中提供了一些常用的操作,比如矩阵的求和,求矩阵的最大最小值等,如果矩阵有多维,可以通过指定维数来得到某一位的基本操作(先列后行)。

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

常用函数


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

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

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

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


One-dimensional

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

Multidimensional

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

Iterating

  1. >>> for row in b:
  2. ... print row
  3. ...
  4. [0 1 2 3]
  5. [10 11 12 13]
  6. [20 21 22 23]
  7. [30 31 32 33]
  8. [40 41 42 43]
  9. ---------------------------------------------------------
  10. >>> for element in b.flat:
  11. ... print element,
  12. ...
  13. 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()等来改变矩阵的大小,下面是一些例子:

  1. >>> a = floor(10*random.random((3,4)))
  2. >>> a
  3. array([[ 7., 5., 9., 3.],
  4. [ 7., 2., 7., 8.],
  5. [ 6., 8., 3., 2.]])
  6. >>> a.shape
  7. (3, 4)
  8. >>> a.ravel() # flatten the array
  9. array([ 7., 5., 9., 3., 7., 2., 7., 8., 6., 8., 3., 2.])
  10. >>> a.shape = (6, 2)
  11. >>> a.transpose()
  12. array([[ 7., 9., 7., 7., 6., 3.],
  13. [ 5., 3., 2., 8., 8., 2.]])
  14. >>> a
  15. array([[ 7., 5.],
  16. [ 9., 3.],
  17. [ 7., 2.],
  18. [ 7., 8.],
  19. [ 6., 8.],
  20. [ 3., 2.]])
  21. >>> a.resize((2,6))
  22. >>> a
  23. array([[ 7., 5., 9., 3., 7., 2.],
  24. [ 7., 8., 6., 8., 3., 2.]])
  25. >>> a.reshape(3,-1) # 当reshape中的参数为-1时,则对应维度的大小会自动计算
  26. array([[ 7., 5., 9., 3.],
  27. [ 7., 2., 7., 8.],
  28. [ 6., 8., 3., 2.]])

Stacking together different arrays

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

  1. >>> a = floor(10*random.random((2,2)))
  2. >>> a
  3. array([[ 1., 1.],
  4. [ 5., 8.]])
  5. >>> b = floor(10*random.random((2,2)))
  6. >>> b
  7. array([[ 3., 3.],
  8. [ 6., 0.]])
  9. >>> vstack((a,b))
  10. array([[ 1., 1.],
  11. [ 5., 8.],
  12. [ 3., 3.],
  13. [ 6., 0.]])
  14. >>> hstack((a,b))
  15. array([[ 1., 1., 3., 3.],
  16. [ 5., 8., 6., 0.]])

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

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

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

  1. >>> r_[1:4,0,4]
  2. 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,可以将矩阵按横坐标和纵坐标进行分割,可以通过指定将数据等分为多少份或者指定分割后所在的列(行)进行分割:

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

英文原文: http://wiki.scipy.org/Tentative_NumPy_Tutorial#head-1529ae93dd5d431ffe3a1001a4ab1a394e70a5f2
MarkDown原文: https://www.zybuluo.com/chanvee/note/89078

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注