我正在使用不同的索引方法。我有以下工作示例:
import numpy as np
x = np.random.rand(321,321)
a = range(0, 300)
b = range(1, 301)
mask = np.zeros(x.shape, dtype=bool)
# a and b are lists
mask[a, b] = True
assert x[a, b].shape == x[mask].shape # passes
assert np.isclose(np.sum(x[mask]), np.sum(x[a, b])) # passes
assert np.allclose(x[mask], x[a, b]) # fails sometimes
当我用一个不同x的项目尝试它时,最后一个断言失败了。这是一个失败的案例:
import numpy as np
x = np.random.rand(431,431)
a = [0, 1, 1, 1, 2, 2, 2, 3]
b = [1, 0, 2, 4, 3, 1, 11, 2]
mask = np.zeros(x.shape, dtype=bool)
# a and b are lists
mask[a, b] = True
assert x[a, b].shape == x[mask].shape # passes
assert np.isclose(np.sum(x[mask]), np.sum(x[a, b])) # passes
assert np.allclose(x[mask], x[a, b]) # fails
谁能解释为什么会发生这个错误?我认为这是因为 mask 对 x 的索引与 (a,b) 不同,但不确定如何。
我想这样做是因为我想轻松获得 x[~mask]
九州编程
当年话下
相关分类