np.where 条件 selects 奇数元素,其中条件指定为 select 偶数
np.where condition selects odd elements where the condition specifies to select the even ones
我正在尝试使用 numpy 进行作业时发现有些奇怪但无法弄清楚。
问题:将arr中的所有奇数替换为-1。
要替换的数组 -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
结果 -> 数组([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1])
我尝试了以下语法:
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) #What went wrong here?
np.where(arr%2==0,arr,-1)
输出很奇怪
array([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1])
这正是我想要的,但请注意 where 条件?我错误地将条件写到 select 偶数元素,但由于某种原因它 select 写了奇数元素。
我用 argwhere 尝试了同样的事情:
arr[np.argwhere((arr%2!=0))] = -1
它给出了预期的结果。那么,np.where 出了什么问题?
一切都按预期运行。查看 numpy.where
文档字符串。您正在选择 arr
条件为真的那些元素,否则为 -1
。对于 2 的倍数的数字,您的条件会产生 True
。
numpy.where(条件)中的第一个参数表示是否为真,保持元素不变。
如果条件为假,则使用numpy.where中提到的第3个参数对元素进行操作。
所以无论你遇到什么行为都是正确的。
参考Numpy文档中给出的例子@https://numpy.org/doc/stable/reference/generated/numpy.where.html
你也可以参考https://www.journaldev.com/37898/python-numpy-where
我正在尝试使用 numpy 进行作业时发现有些奇怪但无法弄清楚。
问题:将arr中的所有奇数替换为-1。
要替换的数组 -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
结果 -> 数组([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1])
我尝试了以下语法:
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) #What went wrong here?
np.where(arr%2==0,arr,-1)
输出很奇怪
array([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1])
这正是我想要的,但请注意 where 条件?我错误地将条件写到 select 偶数元素,但由于某种原因它 select 写了奇数元素。
我用 argwhere 尝试了同样的事情:
arr[np.argwhere((arr%2!=0))] = -1
它给出了预期的结果。那么,np.where 出了什么问题?
一切都按预期运行。查看 numpy.where
文档字符串。您正在选择 arr
条件为真的那些元素,否则为 -1
。对于 2 的倍数的数字,您的条件会产生 True
。
numpy.where(条件)中的第一个参数表示是否为真,保持元素不变。
如果条件为假,则使用numpy.where中提到的第3个参数对元素进行操作。 所以无论你遇到什么行为都是正确的。
参考Numpy文档中给出的例子@https://numpy.org/doc/stable/reference/generated/numpy.where.html 你也可以参考https://www.journaldev.com/37898/python-numpy-where