简体   繁体   English

在python中,如何通过条件对一维数组的对应元素快速设置二维数组的每一行的值?

[英]In python, how to quickly set the value of each row of a 2 dimensional array by condition on the corresponding element of a one dimensional array?

For instance, I have the following numpy arrays:例如,我有以下numpy数组:

a = numpy.array( [ [ 1 , 3 , 3 ] , [ 2 , 5 , 5 ] , [ 3 , 7 , 7 ] ] )
b = numpy.array( [ 1 , 2 , 3 ] )

I want to write a piece of code that will emulate:我想写一段代码来模拟:

a[ a == b ] = 0

which the output will be:输出将是:

[ [ 0 , 3 , 3 ] , [ 0 , 5 , 5 ] , [ 0 , 7 , 7 ] ]

How to achieve this by not applying a for loop.如何通过不应用for循环来实现这一点。 Here it is just an example, in real reality the arrays are very large and for loop takes too much time to run.这里只是一个例子,在现实中数组非常大, for循环需要太多时间来运行。

you could do the following:您可以执行以下操作:

import numpy as np
a = np.array( [ [ 1 , 3 , 3 ] , [ 2 , 5 , 5 ] , [ 3 , 7 , 7 ] ] )
b = np.array( [ 1 , 2 , 3 ] )

def f(b, a):
    return np.where(a == b, 0, a)

print(np.array([*map(f, b, a)]))

which gives:这使:

[[0 3 3]
 [0 5 5]
 [0 7 7]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM