英文:
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]])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论