简体   繁体   English

替换数组中值的最快方法

[英]Fastest way to replace values in array

I have 2 arrays as follow: 我有2个数组,如下所示:

l=
array([[1205, 1420, 1340],
       [1306, 1530, 1045],
       [2001, 135, 1207],
               ...]])

y= 
array([[1200, 1320, 2001],
       [1306, 1530, 1045],
              ...,
       [  0,   3,   0]])

I would like to find the fastest way to replace values (the sub arrays) in l that are in y by [1000,1000,1000]. 我想找到最快的方法,用[1000,1000,1000]替换y中的l中的值(子数组)。

for example I would get: 例如,我会得到:

 l=
array([[1205, 1420, 1340],
   [1000, 1000, 1000],
   [2001, 135, 1207],
           ...]])

So far I've tried a 'for' loop with 'if' condition but it takes too much time. 到目前为止,我已经尝试了带有“ if”条件的“ for”循环,但是这花费了太多时间。

Thanks for your suggestions. 感谢您的建议。

We could use views to view each row as one element, then use np.isin to get a boolean array of presence , use it to index and finally assign - 我们可以使用views将每一行视为一个元素,然后使用np.isin获取存在的布尔数组,将其用于索引并最终分配-

# https://stackoverflow.com/a/45313353/ @Divakar
def view1D(a, b): # a, b are arrays
    a = np.ascontiguousarray(a)
    b = np.ascontiguousarray(b)
    void_dt = np.dtype((np.void, a.dtype.itemsize * a.shape[1]))
    return a.view(void_dt).ravel(),  b.view(void_dt).ravel()

l1D,y1D = view1D(l,y)
l[np.isin(l1D, y1D)] = [1000,1000,1000]

Sample run - 样品运行-

In [36]: l
Out[36]: 
array([[1205, 1420, 1340],
       [1306, 1530, 1045],
       [2001,  135, 1207],
       [   2,    3,    4]])

In [37]: y
Out[37]: 
array([[1200, 1320, 2001],
       [1306, 1530, 1045],
       [   0,    3,    0]])

In [38]: l1D,y1D = view1D(l,y)

In [39]: l[np.isin(l1D, y1D)] = [1000,1000,1000]

In [40]: l
Out[40]: 
array([[1205, 1420, 1340],
       [1000, 1000, 1000],
       [2001,  135, 1207],
       [   2,    3,    4]])

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

相关问题 用列表替换numpy数组中的值的最快方法 - Fastest way to replace values in a numpy array with a list 使用 Python 在数组中用 0 替换负值和用 1 替换大于 1 的值的最快方法是什么? - What is the fastest way to replace negative values with 0 and values greater than 1 with 1 in an array using Python? 如果数组中的值与条件匹配,则用另一个数组中相同位置的值替换数组中的值的最快方法 - fastest way to replace values in an array with the value in the same position in another array if they match a condition 替换numpy数组中所有元素的最快方法 - Fastest way to replace all elements in a numpy array 将数组中的低值归零的最快方法? - Fastest way to zero out low values in array? 通过一组值过滤 numpy 数组的最快方法 - Fastest way to filter a numpy array by a set of values 用另一个 df 中的值替换一个 df 中的值的最快方法 - fastest way to replace values in one df with values from another df 数组索引:在python中用另一组索引替换索引的最快方法 - Array indexing: the fastest way to replace the indexes with another set of indexes in python 在一个数组中查找另一个数组中的值的最快方法 - Fastest way to look for values in an array that are also in another array Vim 最快的换字方式 - Vim fastest way to replace words
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM