在标准阵列中切片多个维度

2024-04-23 11:45:32 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在一行中按多个维度对ndarray进行切片?检查以下代码段中的最后一行。这似乎很基本,但它给了一个惊喜。。。但为什么呢?你知道吗

import numpy as np

# create 4 x 3 array
x = np.random.rand(4, 3)

# create row and column filters
rows = np.array([True, False, True, False])
cols = np.array([True, False, True])

print(x[rows, :].shape == (2, 3))  # True ... OK
print(x[:, cols].shape == (4, 2))  # True ... OK
print(x[rows][:, cols].shape == (2, 2))  # True ... OK
print(x[rows, cols].shape == (2, 2))  # False ... WHY???

Tags: importnumpyfalsetrue代码段createnp切片
1条回答
网友
1楼 · 发布于 2024-04-23 11:45:32

由于rowscols是布尔数组,因此在执行此操作时:

x[rows, cols]

就像:

x[np.where(rows)[0], np.where(cols)[0]]

即:

x[[0, 2], [0, 2]]

(0, 0)(2, 2)处的值。另一方面,做:

x[rows][:, cols]

工作原理如下:

x[[0, 2]][:, [0, 2]]

在本例中返回一个形状(2, 2)。你知道吗

相关问题 更多 >