I have this pandas dataframe: rls[20, 34, 21, 19] censored[260, 0, 0, 380] I am trying to replace non zero values in the censored column with 1s. I tried many different methods, but all of them either return the same copy of the dataframe or change both rls and censored colums which is not what I want. It feels that replace method should work, but I don't know how to specify non zero values data_rls.censored.replace([(!=0), 0], [1, 0], inplace=True)
Asked
Active
Viewed 1,081 times
0
-
whats the dtype of the column ? – Umar.H Feb 19 '20 at 23:48
-
It's pandas series – Sasha Golubeva Feb 20 '20 at 00:05
1 Answers
0
Welcome to SO. Please review how to produce a reproducible example.
You can use the pd.where()
function for your problem.
import pandas as pd
df = pd.DataFrame({'a':[1,3,4,0,0,4,5],'b':[1,3,4,0,0,4,5]})
df.head()
a b
0 1 1
1 3 3
2 4 4
3 0 0
4 0 0
df['a'] = df['a'].where(df['a'] == 0, 1)
df
a b
0 1 1
1 1 3
2 1 4
3 0 0
4 0 0
5 1 4
6 1 5

bwc
- 1,028
- 7
- 18
-
Thank you! I realized that I used where method, but I haven't saved the resulting column. Sorry, working with pandas is still new for me – Sasha Golubeva Feb 20 '20 at 00:33
-
Glad it worked for you. Please consider upvoting and/or marking it as a solution so others can easily identify it as a plausible solution. – bwc Feb 20 '20 at 01:08