[关闭]
@Pigmon 2017-04-09T13:30:50.000000Z 字数 1612 阅读 87

Numpy

Python


import

  1. import numpy as np

arange

  1. # array arange(include, exclude, step)
  2. np.arange(1, 5) # [1 2 3 4]
  3. np.arange(1, 15, 2) # [ 1 3 5 7 9 11 13]
  4. np.arange(5) # [0 1 2 3 4]

linspace

  1. # 在0到2PI之间均匀的生成50个数字
  2. np.linspace(0, 2 * np.pi, 50)

array

  1. tuple1 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
  2. arr1 = np.array(tuple1) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  3. # reshape(row, col)
  4. # [[ 1 2 3 4 5]
  5. # [ 6 7 8 9 10]]
  6. arr2 = arr1.reshape(2, 5)
  7. # shape
  8. arr2.shape; # (2,5)
  9. # 各种运算
  10. arr2.max() # 10
  11. np.max(arr2[1]) # 10
  12. np.min(arr2[0]) # 1
  13. np.max(arr2[1, :3]) # 8 第二行,前3个数中的最大值
  14. np.mean(arr2[0]) # 3.0 第一行平均值
  15. np.sum(arr2[1]) # 40,第二行相加
  16. np.sum(arr2[:,2]) # 11,第三列相加,即 3 + 8
  17. np.sum(arr2, 0) # [ 7 9 11 13 15] 求各列的和
  18. np.sum(arr2, 1) # [15 40] 各行的和
  19. # [[0 0 0]
  20. # [0 0 0]
  21. # [0 0 0]]
  22. mat_o = np.zeros((3, 3), dtype=np.int32) # 参数2可选,默认float
  23. # [[1 0 0]
  24. # [0 1 0]
  25. # [0 0 1]]
  26. mat_i = np.eye(3, dtype=np.int32) # 注意eye只有一个参数,即方阵的阶,如eye(3)代表3阶单位矩阵
  27. # [[1 1 1]
  28. # [1 1 1]
  29. # [1 1 1]]
  30. mat_1 = np.ones((3, 3), dtype=np.int32)
  31. # type
  32. type(mat_1) # <type 'numpy.ndarray'>
  33. # size
  34. print mat_1.size; # 9
  35. # [[1 2 3]
  36. # [4 5 6]
  37. # [7 8 9]]
  38. mat = np.array([1,2,3,4,5,6,7,8,9]).reshape((3,3))
  39. print mat[1, 1] # 5,代表第二行第二列,从0开始
  40. print mat[0] # [1 2 3]
  41. print mat[1] # [4 5 6]
  42. print mat[2] # [7 8 9]
  43. print mat[:1] # [[1 2 3]]
  44. print mat[1:2] # [[4 5 6]]
  45. print mat[2:] # [[7 8 9]]
  46. print mat[1,:2] # [4 5]
  47. # 运算
  48. # [[2 1 1]
  49. # [1 2 1]
  50. # [1 1 2]]
  51. print mat_i + mat_1
  52. # 矩阵乘法 np.dot(mat1, mat2)
  53. # [[ 6 6 6]
  54. # [15 15 15]
  55. # [24 24 24]]
  56. print np.dot(mat, mat_1)
  57. # [[1 2 3]
  58. # [4 5 6]
  59. # [7 8 9]]
  60. print np.dot(mat, mat_i)
  61. # 逐项乘,即 *
  62. # [[1 0 0]
  63. # [0 5 0]
  64. # [0 0 9]]
  65. print mat * mat_i
  66. # 逆矩阵
  67. # [[ 1. 0. 0.]
  68. # [ 0. 1. 0.]
  69. # [ 0. 0. 1.]]
  70. np.linalg.inv(mat_i)
  71. # 转置矩阵
  72. # [[1 4 7]
  73. # [2 5 8]
  74. # [3 6 9]]
  75. mat.transpose()

SymPy,可以输出符号公式的包

  1. import numpy as np
  2. import sympy as sp
  3. a,b,c,d,e,f,g,h,i = sp.symbols('a b c d e f g h i')
  4. mat = np.array([a,b,c,d,e,f,g,h,i]).reshape((3,3))
  5. M = sp.Matrix(mat)
  6. print M # Matrix([[a, b, c], [d, e, f], [g, h, i]])
  7. print M.det() # a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g

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