使用numpy在ndarray中找到n个n的每个实例的索引
我有一个2D数组,我想倒入0到1,反之亦然,但仅在第一行上。
我在下面有一个有关如何做的示例,但它会影响整个ndarray。
np.where((a==0)|(a==1), a^1, a)
For example:
a = np.array([[0,1,0,1], [1,0,0,1]])
print(a)
array([[0, 1, 0, 1],
[1, 0, 0, 1]])
np.where((a==0)|(a==1), a^1, a)
输入:
array([[0, 1, 0, 1],
[1, 0, 0, 1]])
当前输出:
array([[1, 0, 1, 0],
[0, 1, 1, 0]])
所需的输出:
array([[1, 0, 1, 0],
[1, 0, 0, 1]])
谢谢。
I have an 2d array, and I'd like to invert 0 to 1 and vice versa, but only on the first row.
I have an example below on how to do it, but it affects the entire ndarray.
np.where((a==0)|(a==1), a^1, a)
For example:
a = np.array([[0,1,0,1], [1,0,0,1]])
print(a)
array([[0, 1, 0, 1],
[1, 0, 0, 1]])
np.where((a==0)|(a==1), a^1, a)
Input:
array([[0, 1, 0, 1],
[1, 0, 0, 1]])
Current output:
array([[1, 0, 1, 0],
[0, 1, 1, 0]])
Desired output:
array([[1, 0, 1, 0],
[1, 0, 0, 1]])
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需使用:
或
使用
np.logical_not
:Simply Use:
OR
OR use
np.logical_not
:可能
如果 (除了 porwal asnwer 这很容易使用ie
a [0] = 1- a [0]
)您可以根据以下方式将其转换为布尔数组:
It is recommended to use indexing by NumPy if possible, not other modules like
np.where
:if you have just
0
and1
in the array (besides the porwal asnwer that is very easy to use i.e.a[0] = 1 - a[0]
) you can convert to Boolean array based on that as:that can be written in one line as: