0


18 个 实用的Numpy 代码片段总结

Numpy 长期以来一直是 Python 开发人员进行数组操作的通用选择,它是基于C语言构建的这使得它成为执行数组操作的快速和可靠的选择,并且它已经成为机器学习和数据科学必备的基础库。

在本文中,我整理了一些 NumPy 代码的片段,这些代码片段都是在日常开发中经常用到的。

1、创建数组

  1. import numpy as np
  2. new_array = np.array([1,2,3])
  3. print(new_array)
  4. # Output[1 2 3]

2、获取 Numpy 数组的形状、维度和大小

  1. # shape
  2. print(new_array.shape)
  3. # dimensions
  4. print(new_array.ndim)
  5. # size
  6. print(new_array.size)
  7. # Output(3,)
  8. 1
  9. 3

3、查看Numpy数组中元素的类型

  1. array = np.arange(0,10,1)
  2. print(array.dtype)
  3. # Output
  4. int64

4、获取数组中每个元素的占用字节大小

  1. array = np.array([1,2])
  2. print(array.itemsize)
  3. # Output
  4. 8

5、创建时指定数组的类型

  1. array = np.array([[1,2], [3,4]], dtype=complex)
  2. array
  3. # Output
  4. array([[1.+0.j, 2.+0.j],
  5. [3.+0.j, 4.+0.j]])

6、使用占位符创建数组

  1. # 全零数组
  2. array = np.zeros((3,4))
  3. print(array)
  4. print("---")
  5. # 全1数组
  6. array = np.ones((1,2))
  7. print(array)
  8. print("---")
  9. # shape (2,3)的空数组,随机产生数据
  10. array = np.empty((2,3))
  11. print(array)
  12. print("---")
  13. # Output
  14. [[0. 0. 0. 0.]
  15. [0. 0. 0. 0.]
  16. [0. 0. 0. 0.]]
  17. ---
  18. [[1. 1.]]
  19. ---
  20. [[4.67280967e-310 0.00000000e+000 0.00000000e+000]
  21. [0.00000000e+000 0.00000000e+000 0.00000000e+000]]
  22. ---

7、创建序列

  1. # 使用 np.arange 创建一个从 0 到 42 个元素的序列,步长1
  2. array = np.arange(0,42,1)
  3. print(array)
  4. print("---")
  5. # 使用 np.linspace 在 0 到 100 之间插入 42 个元素
  6. array = np.linspace(0,100,42)
  7. print(array)
  8. print("---")
  9. # Output
  10. [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
  11. 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41]
  12. ---
  13. [ 0. 2.43902439 4.87804878 7.31707317 9.75609756
  14. 12.19512195 14.63414634 17.07317073 19.51219512 21.95121951
  15. 24.3902439 26.82926829 29.26829268 31.70731707 34.14634146
  16. 36.58536585 39.02439024 41.46341463 43.90243902 46.34146341
  17. 48.7804878 51.2195122 53.65853659 56.09756098 58.53658537
  18. 60.97560976 63.41463415 65.85365854 68.29268293 70.73170732
  19. 73.17073171 75.6097561 78.04878049 80.48780488 82.92682927
  20. 85.36585366 87.80487805 90.24390244 92.68292683 95.12195122
  21. 97.56097561 100. ]
  22. ---

8、Numpy中的数学函数

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # sine function
  4. x = np.linspace(0,2*np.pi, 100)
  5. f = np.sin(x)
  6. plt.figure(figsize=(15,7))
  7. plt.subplot(1,3,1)
  8. plt.plot(f, color="green")
  9. plt.title("np.sin(x)")
  10. # cosine function
  11. f = np.cos(x)
  12. plt.subplot(1,3,2)
  13. plt.plot(f, color="blue")
  14. plt.title("np.cos(x)")
  15. # tangent function
  16. f = np.tan(x)
  17. plt.subplot(1,3,3)
  18. plt.plot(f, color="red")
  19. plt.title("np.tan(x)")
  20. plt.show()

9、通过在每个坐标上执行函数来创建数组

  1. some_function = lambda x: np.cos(x)+1
  2. array = np.fromfunction(some_function, (100,))
  3. plt.figure(figsize=(15,7))
  4. plt.plot(array, color="green")
  5. plt.title("np.cos(x) +1")
  6. plt.show()

10、遍历Numpy数组的所有元素

  1. a = np.arange(0,23,1)
  2. for i in a.flat:
  3. print(i)
  4. # Output
  5. 0
  6. 1
  7. 2
  8. ...
  9. 22

11、获取浮点数的下限

  1. np.floor(10.5)
  2. 10.0

12、使用.ravel()压扁数组

  1. array = np.full(shape=(5,5),fill_value=10)
  2. print(array)
  3. print("---")
  4. print("Flattened array:")
  5. print(array.ravel())
  6. # Output
  7. [[10 10 10 10 10]
  8. [10 10 10 10 10]
  9. [10 10 10 10 10]
  10. [10 10 10 10 10]
  11. [10 10 10 10 10]]
  12. ---
  13. Flattened array:
  14. [10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
  15. 10]

13、获取一个数组的转置

  1. array = np.random.random((2,5))
  2. print(array)
  3. print(array.T)
  4. [[0.18735704 0.22800582 0.02552177 0.93552346 0.20720663]
  5. [0.74303284 0.1897481 0.91389602 0.23099501 0.07565492]]
  6. [[0.18735704 0.74303284]
  7. [0.22800582 0.1897481 ]
  8. [0.02552177 0.91389602]
  9. [0.93552346 0.23099501]
  10. [0.20720663 0.07565492]]

14、使用. shape()和.resize()进行重塑

  1. a = np.random.randint(100,size=(3,4))
  2. print(a)
  3. a_reshaped = np.reshape(a, (1,12))
  4. print(a_reshaped)
  5. # 使用.resize()方法
  6. a.resize((1,12))
  7. # Output
  8. [[29 18 39 24]
  9. [53 45 49 8]
  10. [90 75 61 61]]
  11. [[29 18 39 24 53 45 49 8 90 75 61 61]]

15、将数组沿不同轴进行堆叠

  1. a = np.random.random((2,2))
  2. print(a)
  3. b = np.random.random((2,2))
  4. print(b)
  5. # 沿垂直轴堆叠(获得更多行)
  6. print(np.vstack((a,b)))
  7. print(np.vstack((a,b)).shape)
  8. # 沿水平轴堆叠(获得更多列)
  9. print(np.hstack((a,b)))
  10. print(np.hstack((a,b)).shape)
  11. # column_stack列叠加
  12. print(np.column_stack((a,b)))
  13. # Output
  14. [[0.67028492 0.86322792]
  15. [0.38906266 0.36967583]]
  16. [[0.51419553 0.21937852]
  17. [0.50375453 0.31634597]]
  18. [[0.67028492 0.86322792]
  19. [0.38906266 0.36967583]
  20. [0.51419553 0.21937852]
  21. [0.50375453 0.31634597]]
  22. (4, 2)
  23. [[0.67028492 0.86322792 0.51419553 0.21937852]
  24. [0.38906266 0.36967583 0.50375453 0.31634597]]
  25. (2, 4)
  26. [[0.67028492 0.86322792 0.51419553 0.21937852]
  27. [0.38906266 0.36967583 0.50375453 0.31634597]]

16、将一个数组拆分为几个较小的数组

使用hsplit,通过指定要返回的相同shape的array的数量,或者通过指定分割应该发生之后的列来沿着其横轴拆分原array。vsplit沿着垂直轴分割,其分割方式与hsplit用法相同

  1. # 沿着水平轴将数组拆分为5个较小的数组
  2. a = np.arange(0, 5, 1)
  3. print("Horizontal split")
  4. print(np.hsplit(a, 5))
  5. print("---")
  6. # 沿着垂直轴将数组拆分成5个更小的数组
  7. a = np.random.random((5,5))
  8. print("Vertical split")
  9. print(np.vsplit(a, 5))
  10. Horizontal split
  11. [array([0]), array([1]), array([2]), array([3]), array([4])]
  12. ---
  13. Vertical split
  14. [array([[0.69059321, 0.55703093, 0.20019592, 0.19697317, 0.37278251]]), array([[0.24597633, 0.87216661, 0.634432 , 0.35326185, 0.03130537]]), array([[0.18063077, 0.45045441, 0.06882852, 0.91273837, 0.07332161]]), array([[0.61738939, 0.11291748, 0.73152623, 0.49177006, 0.95750985]]), array([[0.90212777, 0.53825846, 0.86733505, 0.76165564, 0.17337721]])]

17、数组的浅拷贝

.view() 方法创建了一个与原数组对象相同的对象,它创建了该数组的浅拷贝,浅拷贝只复制指向某个对象的指针,而不复制对象数据,新旧对象还是共享同一块内存。所以如果其中一个对象改变了内存的数值,就会影响到另一个对象,也就是说一个对象的数值改变了,其他的也会改变(使用相同的内存)。

  1. a = np.array([
  2. [0,1,2,3,4],
  3. [5,6,7,8,9],
  4. [10,11,12,13,14]
  5. ])
  6. array_object = np.arange(0,10,1)
  7. shallow_copy_object = array_object.view() # shallow copy
  8. print("Array")
  9. print(array_object)
  10. print(f"Id = {id(array_object)}")
  11. print("---")
  12. print("Shallow Copy")
  13. print(shallow_copy_object)
  14. print(f"Id = {id(shallow_copy_object)}")
  15. print("---")
  16. shallow_copy_object[0] = 200
  17. print("After assigment: shallow_copy_object[0] = 200")
  18. print("Array")
  19. print(array_object)
  20. print("Shallow copy")
  21. print(shallow_copy_object)
  22. # Output
  23. Array
  24. [0 1 2 3 4 5 6 7 8 9]
  25. Id = 139980496768528
  26. ---
  27. Shallow Copy
  28. [0 1 2 3 4 5 6 7 8 9]
  29. Id = 139980496768720
  30. ---
  31. After assigment: shallow_copy_object[0] = 200
  32. Array
  33. [200 1 2 3 4 5 6 7 8 9]
  34. Shallow copy
  35. [200 1 2 3 4 5 6 7 8 9]

18、数组的深拷贝

copy 方法复制对象及其数据的完整副本。完全拷贝了一个副本,内部元素地址都不一样,数值的改变不会互相影响。

  1. array_object = np.arange(0, 23, 1)
  2. deep_copy_object = array_object.copy()
  3. print(deep_copy_object is array_object)
  4. print("Array")
  5. print(array_object)
  6. print(f"Array id = {id(array_object)}")
  7. print("---")
  8. print("Deep Copy")
  9. print(deep_copy_object)
  10. print(f"Deep copy id = {id(deep_copy_object)}")
  11. print("---")
  12. deep_copy_object[0] = 234
  13. print("After assignment: deep_copy_object[0] = 234")
  14. print("Array")
  15. print(array_object)
  16. print("Deep copy")
  17. print(deep_copy_object)
  18. False
  19. Array
  20. [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22]
  21. Array id = 139980498767472
  22. ---
  23. Deep Copy
  24. [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22]
  25. Deep copy id = 139980496039824
  26. ---
  27. After assignment: deep_copy_object[0] = 234
  28. Array
  29. [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22]
  30. Deep copy
  31. [234 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
  32. 18 19 20 21 22]

作者:Lucas Soares

“18 个 实用的Numpy 代码片段总结”的评论:

还没有评论