I have a dataframe
df=
A B C
1 2 55
0 44 0
0 0 0
and I want to change values to 1 if the value is >0.
Is this the right approach: df.loc[df>0,]=1
to give:
A B C
1 1 1
0 1 0
0 0 0
I have a dataframe
df=
A B C
1 2 55
0 44 0
0 0 0
and I want to change values to 1 if the value is >0.
Is this the right approach: df.loc[df>0,]=1
to give:
A B C
1 1 1
0 1 0
0 0 0
Use clip_upper
:
df = df.clip_upper(1)
print (df)
A B C
0 1 1 1
1 0 1 0
2 0 0 0
Numpy alternative:
df = pd.DataFrame(np.clip(df.values, a_min=0, a_max=1),
index=df.index,
columns=df.columns)
print (df)
A B C
0 1 1 1
1 0 1 0
2 0 0 0
And solution if no negative integer values - compare by ge
(>=
) and cast mask to integers:
print (df.ge(1))
A B C
0 True True True
1 False True False
2 False False False
df = df.ge(1).astype(int)
print (df)
A B C
0 1 1 1
1 0 1 0
2 0 0 0
You can do this:
df.clip_upper(1)
or this:
df.where(df < 1, other=1)