NumPy 索引、切片和迭代

2021-09-03 17:01 更新

一维数组可以被索引、切片和迭代,就像列表和其他Python 序列一样。

  1. >>> a = np.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. >>> # equivalent to a[0:6:2] = 1000;
  9. >>> # from start to position 6, exclusive, set every 2nd element to 1000
  10. >>> a[:6:2] = 1000
  11. >>> a
  12. array([1000, 1, 1000, 27, 1000, 125, 216, 343, 512, 729])
  13. >>> a[::-1] # reversed a
  14. array([ 729, 512, 343, 216, 125, 1000, 27, 1000, 1, 1000])
  15. >>> for i in a:
  16. ... print(i**(1 / 3.))
  17. ...
  18. 9.999999999999998
  19. 1.0
  20. 9.999999999999998
  21. 3.0
  22. 9.999999999999998
  23. 4.999999999999999
  24. 5.999999999999999
  25. 6.999999999999999
  26. 7.999999999999999
  27. 8.999999999999998

多维数组的每个轴可以有一个索引,这些索引在用逗号分隔的元组中给出:

  1. >>> def f(x, y):
  2. ... return 10 * x + y
  3. ...
  4. >>> b = np.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]])

当提供的索引少于轴数时,缺失的索引被视为完整切片:

  1. >>> b[-1] # the last row. Equivalent to b[-1, :]
  2. array([40, 41, 42, 43])

括号中的b[i]表达式被视为i 后跟:代表其余轴所需的尽可能多的实例。NumPy 还允许您使用点作为 .b[i, ...]

...)的点根据需要,以产生一个完整的索引元组表示为许多冒号。例如,如果x是一个有 5 个轴的数组,则

  • x[1, 2, ...]相当于,x[1, 2, :, :, :]
  • x[..., 3]到和x[:, :, :, :, 3]
  • x[4, ..., 5, :]到。x[4, :, :, 5, :]

  1. >>> c = np.array([[[ 0, 1, 2], # a 3D array (two stacked 2D arrays)
  2. ... [ 10, 12, 13]],
  3. ... [[100, 101, 102],
  4. ... [110, 112, 113]]])
  5. >>> c.shape
  6. (2, 2, 3)
  7. >>> c[1, ...] # same as c[1, :, :] or c[1]
  8. array([[100, 101, 102],
  9. [110, 112, 113]])
  10. >>> c[..., 2] # same as c[:, :, 2]
  11. array([[ 2, 13],
  12. [102, 113]])

迭代多维数组是相对于第一个轴完成的:

  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]

但是,如果要对数组中的每个元素执行操作,可以使用flat属性,它是数组所有元素的迭代器:

  1. >>> for element in b.flat:
  2. ... print(element)
  3. ...
  4. 0
  5. 1
  6. 2
  7. 3
  8. 10
  9. 11
  10. 12
  11. 13
  12. 20
  13. 21
  14. 22
  15. 23
  16. 30
  17. 31
  18. 32
  19. 33
  20. 40
  21. 41
  22. 42
  23. 43
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号