Reputation: 905
I have a df as below
I want to make this df binary as follows
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.
Upvotes: 2
Views: 74
Reputation: 13247
of course it is possible by func, it can be done with just operator
(df > 0) * 1
Upvotes: 1
Reputation: 862901
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)
Upvotes: 4