官方文档:https://numpy.org/doc/stable/reference/generated/numpy.ix_.html#numpy.ix_,给出的用法是:
numpy.ix_(*args)
'''
Construct an open mesh from multiple sequences.
This function takes N 1-D sequences and returns N outputs with N dimensions each, such that the shape is 1 in all but one dimension and the dimension with the non-unit shape value cycles through all N dimensions.
Using ix_ one can quickly construct index arrays that will index the cross product. a[np.ix_([1,3],[2,5])] returns the array [[a[1,2] a[1,5]], [a[3,2] a[3,5]]].
'''
看不太懂,操作代码也是不懂:
a = np.arange(10).reshape(2, 5)
print(a)
ixgrid = np.ix_([0, 1], [2, 4])
print("-" * 10)
print(ixgrid)
print("-" * 10)
print(a[ixgrid])
'''
输出:
[[0 1 2 3 4]
[5 6 7 8 9]]
----------
(array([[0],
[1]]), array([[2, 4]]))
----------
[[2 4]
[7 9]]
'''
参考链接中给出的:
'''
Its main use is to create an open mesh to select specific indices from an array (specific sub-array).
An easy example to understand it is: Say you have an array of shape (5,5),
and you would like to select the sub-array that is constructed from selecting
rows 1 and 3 and columns 0 and 3.
You can use np.ix_ to create such (index) mesh to be able to select sub-array as follows:
'''
a = np.arange(5*5).reshape(5,5)
print(a)
print("-" * 10)
sub_indices = np.ix_([1,3],[0,3])
print(sub_indices)
print("-" * 10)
print(a[sub_indices])
'''
输出:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
----------
(array([[1],
[3]]), array([[0, 3]]))
----------
[[ 5 8]
[15 18]]
'''
通过上面的操作,得到的是'a'中行索引为1、3和列索引为0、3的元素:即'a[1, 0], a[1, 3], a[3, 0], a[3, 3]'。
col 0 col 3
| |
v v
[[ 0 1 2 3 4]
[ 5 6 7 8 9] <- row 1
[10 11 12 13 14]
[15 16 17 18 19] <- row 3
[20 21 22 23 24]]
从np.ix_返回的结果看,函数第一个参数返回‘行的索引’,第二个参数返回‘列的索引’,第三个参数返回‘深度的索引’,以此类推。
当索引三维array时:
b = np.arange(5*5*5).reshape(5, 5, 5)
print(b)
print("-" * 10)
sub_indices = np.ix_([1,3],[0,3],[1,3])
print(sub_indices)
print("-" * 10)
print(b[sub_indices])
'''
输出:
[[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[ 10 11 12 13 14]
[ 15 16 17 18 19]
[ 20 21 22 23 24]]
[[ 25 26 27 28 29]
[ 30 31 32 33 34]
[ 35 36 37 38 39]
[ 40 41 42 43 44]
[ 45 46 47 48 49]]
[[ 50 51 52 53 54]
[ 55 56 57 58 59]
[ 60 61 62 63 64]
[ 65 66 67 68 69]
[ 70 71 72 73 74]]
[[ 75 76 77 78 79]
[ 80 81 82 83 84]
[ 85 86 87 88 89]
[ 90 91 92 93 94]
[ 95 96 97 98 99]]
[[100 101 102 103 104]
[105 106 107 108 109]
[110 111 112 113 114]
[115 116 117 118 119]
[120 121 122 123 124]]]
----------
(array([[[1]],
[[3]]]), array([[[0],
[3]]]), array([[[1, 3]]]))
----------
[[[26 28]
[41 43]]
[[76 78]
[91 93]]]
'''
通过上面的操作,得到的是'b'中'b[1, 0, 1], b[1, 0, 3], b[1, 3, 1], b[1, 3, 3],b[3, 0, 1], b[3, 0, 3], b[3, 3, 1], b[3, 3, 3]'。
参考:
https://stackoverflow.com/questions/62505046/what-does-numpy-ix-function-do-and-what-is-the-output-used-for