z = np.array([1, 2, 3, 4])
x = np.array([4, 2, 3, 5])
n = 1
これらの 2 つの配列を要素単位で比較したいのですが、x の要素とは異なる z の要素のみに n を追加したいと考えています。
答えは次のとおりです。
z = [2, 2, 3, 5]
z = np.array([1, 2, 3, 4])
x = np.array([4, 2, 3, 5])
n = 1
これらの 2 つの配列を要素単位で比較したいのですが、x の要素とは異なる z の要素のみに n を追加したいと考えています。
答えは次のとおりです。
z = [2, 2, 3, 5]
np.where を使用した別のソリューション
#np.where checks if the condition is met, if yes set the value to z, otherwise z+n.
np.where(z==x, z,z+n)
Out[1257]: array([2, 2, 3, 5])
マスクを取得し、スケーリングし、その場で追加を行います -
z += n*(z!=x)
マスクだけを使用した別のアプローチ -
z[z!=x] += n
サンプルラン -
In [176]: z = np.array([1, 2, 3, 4])
...: x = np.array([4, 2 ,3 ,5])
...: n = 1
...:
In [177]: z += n*(z!=x)
In [178]: z
Out[178]: array([2, 2, 3, 5])
In [179]: z = np.array([1, 2, 3, 4])
In [180]: z[z!=x] += n
In [181]: z
Out[181]: array([2, 2, 3, 5])
実行時テスト -
アプローチ -
def app1(z, x, n):
z += n*(z!=x)
return z
def app2(z, x, n):
z[z!=x] += n
return z
def where_based(z, x, n): # @Allen's soln
z = np.where(z==x, z,z+n)
return z
タイミング -
In [205]: z = np.random.randint(0,9,(1000000))
...: x = np.random.randint(0,9,(1000000))
...: n = 5
...:
...: zc1 = z.copy()
...: zc2 = z.copy()
...: zc3 = z.copy()
...:
In [206]: %timeit app1(zc1, x, n)
100 loops, best of 3: 2.82 ms per loop
In [207]: %timeit app2(zc2, x, n)
100 loops, best of 3: 7.95 ms per loop
In [208]: %timeit where_based(zc3, x, n)
100 loops, best of 3: 4.51 ms per loop