替换数组中值的最快方法 [英] Fastest way to replace values in array
本文介绍了替换数组中值的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个数组,如下所示:
I have 2 arrays as follow:
l=
array([[1205, 1420, 1340],
[1306, 1530, 1045],
[2001, 135, 1207],
...]])
y=
array([[1200, 1320, 2001],
[1306, 1530, 1045],
...,
[ 0, 3, 0]])
我想找到最快的方法,用[1000,1000,1000]替换y中的l中的值(子数组).
I would like to find the fastest way to replace values (the sub arrays) in l that are in y by [1000,1000,1000].
例如,我会得到:
l=
array([[1205, 1420, 1340],
[1000, 1000, 1000],
[2001, 135, 1207],
...]])
到目前为止,我已经尝试了带有'if'条件的'for'循环,但是这花费了太多时间.
So far I've tried a 'for' loop with 'if' condition but it takes too much time.
感谢您的建议.
推荐答案
我们可以使用 views
将每一行视为一个元素,然后使用 np.isin
来获取 presence 的布尔数组,用它索引并最终分配-
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 -
# 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]
样品运行-
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]])
这篇关于替换数组中值的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文