我有一个3d NumPy数组,我想从中获取很多切片。这些切片在第一和第二维度上具有一个或多个的长度,而第三个切片将完整地返回。切片应始终为3d。
我的尝试:
import numpy as np
a = np.zeros((1000, 10, 100))
row_sets = ([19, 20], [21])
col_sets = ([6], [7, 8])
for rows in row_sets:
for cols in col_sets:
b = a[[rows], [cols]]
print(rows, cols, b.shape)
结果:
[19, 20] [6] (1, 2, 100)
[19, 20] [7, 8] (1, 2, 100)
[21] [6] (1, 1, 100)
[21] [7, 8] (1, 2, 100)
如果我从切片中删除嵌套括号:
b = a[rows, cols]
我在第二维中看起来是同一个问题,并且不保留维度:
[19, 20] [6] (2, 100)
[19, 20] [7, 8] (2, 100)
[21] [6] (1, 100)
[21] [7, 8] (2, 100)
我要找的结果是这样的:
[19, 20] [6] (2, 1, 100)
[19, 20] [7, 8] (2, 2, 100)
[21] [6] (1, 1, 100)
[21] [7, 8] (1, 2, 100)
答案 0 :(得分:2)
通过使用整数列表作为索引来触发 advanced indexing ,这会减少结果数组的维数,如果要对数组进行切片,可以使用{{ 3}}从int列表中重建切片索引:
for rows in row_sets:
for cols in col_sets:
b = a[np.ix_(rows, cols)]
print(rows, cols, b.shape)
#[19, 20] [6] (2, 1, 100)
#[19, 20] [7, 8] (2, 2, 100)
#[21] [6] (1, 1, 100)
#[21] [7, 8] (1, 2, 100)