当NumPy数组的布尔掩码只是一个单一值时会发生什么情况。

huangapple go评论130阅读模式
英文:

what happens when boolean mask of numpy array is just a single value

问题

我知道布尔数组可以用作NumPy数组中的掩码。但是当我在NumPy数组中使用单个值作为掩码时,奇怪的事情发生了:

x = [1,2,3,4,5]
result = np.array(x)[True]
print(result)

结果变成了[[1 2 3 4 5]]。为什么会有双括号?Python在这种情况下做了什么?

英文:

I know that boolean array can be used as a mask in a numpy array.
But when I use a single value as a mask in a numpy array, strange thing happened:

x = [1,2,3,4,5] 
result = np.array(x)[True]
print(result)

It turns out to be [[1 2 3 4 5]]. Why there is a double bracket? What does Python do in this case?

答案1

得分: 1

I think this is due to broadcasting, as your input array doesn't have the correct shape.

To perform real boolean indexing, you would need to pass a list:

np.array(x)[[True, False, True, False, True]]
# array([1, 3, 5])

Obviously with [[True]] this wouldn't work as the shape is mismatching:

np.array(x)[[True]]
# IndexError: boolean index did not match indexed array along dimension 0;
# dimension is 5 but corresponding boolean dimension is 1

When you run np.array(x)[True] this is more or less equivalent to:

np.array(x).reshape((1, -1))[[True]]
# array([[1, 2, 3, 4, 5]])
英文:

I think this is due to broadcasting, as your input array doesn't have the correct shape.

To perform real boolean indexing, you would need to pass a list:

np.array(x)[[True, False, True, False, True]]
# array([1, 3, 5])

Obviously with [[True]] this wouldn't work as the shape is mismatching:

np.array(x)[[True]]
# IndexError: boolean index did not match indexed array along dimension 0;
# dimension is 5 but corresponding boolean dimension is 1

When you run np.array(x)[True] this is more or less equivalent to:

np.array(x).reshape((1, -1))[[True]]
# array([[1, 2, 3, 4, 5]])

huangapple
  • 本文由 发表于 2023年5月17日 16:24:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76269989.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定