Home > Software engineering >  replace all values in all columns based on condition
replace all values in all columns based on condition

Time:12-20

I have a df as below

enter image description here

I want to make this df binary as follows

enter image description here

I tried

df[:]=np.where(df>0, 1, 0)

but with this I am losing my df index. I can try this on all columns one by one or use loop but I think there would be some easy & quick way to do this.

CodePudding user response:

You can convert boolean mask by DataFrame.gt to integers:

df1 = df.gt(0).astype(int)

Or use DataFrame.clip if integers and no negative values:

df1 = df.clip(upper=1)

Your solution should working with loc:

df.loc[:] = np.where(df>0, 1, 0)

CodePudding user response:

of course it is possible by func, it can be done with just operator

(df > 0) * 1

CodePudding user response:

Without using numpy:

df[df>0]=0
  • Related