The Python Oracle

Replace values in array using mask and other array

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping

--

Chapters
00:00 Replace Values In Array Using Mask And Other Array
01:20 Accepted Answer Score 6
01:53 Thank you

--

Full question
https://stackoverflow.com/questions/5212...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #arrays #pandas #numpy #indexing

#avk47



ACCEPTED ANSWER

Score 6


numpy solution:

Its pretty straightforward like this:

# convert frm to a numpy array:
frm = np.array(frm)
# create a copy of frm so you don't modify original array:
to = frm.copy()

# mask to, and insert your replacement values:
to[mask] = repl

Then to returns:

>>> to
array([  1, 200,   3, 400, 500])

pandas solution:

if your dataframe looks like:

>>> df
   column
0       1
1       2
2       3
3       4
4       5

Then you can use loc:

df.loc[mask,'column'] = repl

Then your dataframe looks like:

>>> df
   column
0       1
1     200
2       3
3     400
4     500