以下实例获取(0,0),(1,1),(2,0)位置处的元素

import numpy as np
x = np.array([[1, 2], [3, 4], [5, 6]])
print(x)
y = x[[0, 1, 2], [0, 1, 0]]
print(y)


#输出
[[1 2]
 [3 4]
 [5 6]]
[1 4 5]

获取4×3数组中4个角的元素

import numpy as np
x = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]])
print(x)
rows = np.array([[0, 0], [3, 3]])
cols = np.array([[0, 2], [0, 2]])
y = x[rows, cols]
print(y)

#输出
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
[[ 0  2]
 [ 9 11]]

可以借助切片 :或 …与索引数组组合

import numpy as np
x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(x)
a = x[1:3, 1:3]
print(a)
b = x[1:3, [1, 2]]
print(b)
c = x[..., 1:]
print(c)

#输出
[[1 2 3]
 [4 5 6]
 [7 8 9]]
[[5 6]
 [8 9]]
[[5 6]
 [8 9]]
[[2 3]
 [5 6]
 [8 9]]
Categories: python

0 Comments

发表评论

Avatar placeholder

邮箱地址不会被公开。 必填项已用*标注