Replace values in array using mask and other array
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Intrigue Looping
--
Chapters
00:00 Question
01:42 Accepted answer (Score 5)
02:30 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
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Intrigue Looping
--
Chapters
00:00 Question
01:42 Accepted answer (Score 5)
02:30 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