gpt4 book ai didi

python - 在没有循环的情况下将 numpy 数组中的 1's to 0 and 0' s 更改为 1

转载 作者:行者123 更新时间:2023-11-28 19:36:34 28 4
gpt4 key购买 nike

假设我有一个 numpy 数组,我想在其中将所有 1 交换为 0,将所有 0 交换为 1(该数组将具有其他值,并且 0 和 1 没有什么特别之处)。当然,我可以遍历数组并一个一个地更改值。

是否有可以推荐使用的有效方法? np.where() 方法有这个操作的选项吗?

最佳答案

这是使用 np.where 的一种方法,并在给定值是 01 时对其进行按位 XOR:

np.where((a==0)|(a==1), a^1, a)

例如:

a = np.array([[0,1,2,1], [1,2,0,3]])
print(a)
array([[0, 1, 2, 1],
[1, 2, 0, 3]])

np.where((a==0)|(a==1), a^1, a)

array([[1, 0, 2, 0],
[0, 2, 1, 3]])

关于python - 在没有循环的情况下将 numpy 数组中的 1's to 0 and 0' s 更改为 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56594598/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com