Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Value in Numpy array, with Value in a second Numpy array, Given Criteria

Tags:

python

numpy

I have 2 large arrays with the exact same ammount of elements.

Array1=[[1,2,3][1,1,2]]
Array2=[[0,2,0][3,1,3]]

if Element in Array1="1", Replace "1" with whatever is in the same place as Array2

Output=[[0,2,3][3,1,2]]

Should be easy, but this late on a friday has my brains scrambled.

like image 440
user2624599 Avatar asked Feb 11 '26 07:02

user2624599


2 Answers

import numpy as np

Array1 = np.array([[1,2,3], [1,1,2]])
Array2 = np.array([[0,2,0], [3,1,3]])

b = np.where(Array1 == 1)

Array1[b] = Array2[b]

Result:

>>> Array1
array([[0, 2, 3],
       [3, 1, 2]])

As jorgeca pointed out the above solution can be reduced to:

b = Array1 == 1
Array1[b] = Array2[b]
like image 149
Akavall Avatar answered Feb 15 '26 23:02

Akavall


This one's based on Akaval's solution, but in one line. It takes advantage of other features of np.where():

import numpy as np
Array1 = np.array([[1,2,3], [1,1,2]])  
Array2 = np.array([[0,2,0], [3,1,3]])

Output = np.where(Array1 == 1, Array2, Array1)
like image 45
Dan Avatar answered Feb 16 '26 01:02

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!