Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 更改numpy数组中的项_Python_Numpy_Matplotlib - Fatal编程技术网

Python 更改numpy数组中的项

Python 更改numpy数组中的项,python,numpy,matplotlib,Python,Numpy,Matplotlib,我想根据以下条件(玩具代码)将数组A(轴=1)中的所有项更改为0: 将numpy导入为np A=np.数组([[1,3],[2,5],[6,2]]) B=np.数组([[1,1,0,0,0],[1,0,0,2,0],[0,0,2,2],[0,0,0,2,0],[6,6,0,0,0]) 对于我来说,在一个: 如果i[1]>>B 数组([[1,1,0,0,0], [1, 0, 0, 2, 0], [0, 0, 2, 2, 2], [0, 0, 0, 2, 0], [0, 0, 0, 0, 0]])

我想根据以下条件(玩具代码)将数组A(轴=1)中的所有项更改为0:

将numpy导入为np
A=np.数组([[1,3],[2,5],[6,2]])
B=np.数组([[1,1,0,0,0],[1,0,0,2,0],[0,0,2,2],[0,0,0,2,0],[6,6,0,0,0])
对于我来说,在一个:
如果i[1]>>B
数组([[1,1,0,0,0],
[1, 0, 0, 2, 0],
[0, 0, 2, 2, 2],
[0, 0, 0, 2, 0],
[0, 0, 0, 0, 0]])

但是,用简单的方式来说,这不是“for”循环:)谢谢

您可以使用条件列表理解来创建元组对中第一个值的列表,其中第二个值小于或等于2(在
a
的示例中,它是最后一个给出值
6

然后使用切片与查找
B
中包含在上一条件值中的元素,然后将这些值设置为零

target_val = 2
B[np.isin(B, [a[0] for a in A if a[1] <= target_val])] = 0

>>> B
array([[1, 1, 0, 0, 0],
       [1, 0, 0, 2, 0],
       [0, 0, 2, 2, 2],
       [0, 0, 0, 2, 0],
       [0, 0, 0, 0, 0]])

一行:
B[np.isin(B,A[A[:,1]理解可能不算作for循环,但它也没有充分利用Numpy:)@KarlKnechtel在样本量为100k的情况下,我认为我的方法稍微快一点(5.27ms vs 5.77)。我还添加了
(1,1)
A
给一个额外的数据点。
np.其中
方法几乎花费了2倍的时间。有趣的是,一如既往,在进行优化工作时,没有任何东西可以替代实际的性能基准。与综合方法相比,基本上
A[A[:,1]是的,是的,这就是我一直在寻找的解决方案。非常感谢您的帮助和解释。祝您一切顺利!
target_val = 2
B[np.isin(B, [a[0] for a in A if a[1] <= target_val])] = 0

>>> B
array([[1, 1, 0, 0, 0],
       [1, 0, 0, 2, 0],
       [0, 0, 2, 2, 2],
       [0, 0, 0, 2, 0],
       [0, 0, 0, 0, 0]])
np.where(np.isin(B, [a[0] for a in A if a[1] <= target_val]), 0, B)
c = A[:, 1] <= 2 # broadcast the original `if i[1]<=2:` check along axis=1
# i.e., mask A according to where the second values of the pairs are <= 2
d = c[:, 0] # index with the mask, and select the old `i[0]` values, here just `6`
e = np.isin(B, d) # mask B according to where the values are in the above
B[e] = 0 # and zero out those positions, i.e. where the old B value is 6