NumPy 索引、切片和迭代

2021-09-03 17:01 更新

一維數(shù)組可以被索引、切片和迭代,就像列表和其他Python 序列一樣。

>>> a = np.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])
>>> # equivalent to a[0:6:2] = 1000;
>>> # from start to position 6, exclusive, set every 2nd element to 1000
>>> a[:6:2] = 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.))
...
9.999999999999998
1.0
9.999999999999998
3.0
9.999999999999998
4.999999999999999
5.999999999999999
6.999999999999999
7.999999999999999
8.999999999999998

多維數(shù)組的每個軸可以有一個索引,這些索引在用逗號分隔的元組中給出:

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

當(dāng)提供的索引少于軸數(shù)時,缺失的索引被視為完整切片:

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

括號中的b[i]表達(dá)式被視為i?后跟:代表其余軸所需的盡可能多的實例。NumPy 還允許您使用點(diǎn)作為?.b[i,?...]

...)的點(diǎn)根據(jù)需要,以產(chǎn)生一個完整的索引元組表示為許多冒號。例如,如果x是一個有 5 個軸的數(shù)組,則

  • x[1,?2,?...]相當(dāng)于,x[1,?2,?:,?:,?:]
  • x[...,?3]到和x[:,?:,?:,?:,?3]
  • x[4,?...,?5,?:]到。x[4,?:,?:,?5,?:]

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

迭代多維數(shù)組是相對于第一個軸完成的:

>>> 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]

但是,如果要對數(shù)組中的每個元素執(zhí)行操作,可以使用flat屬性,它是數(shù)組所有元素的迭代器:

>>> 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
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號