My DataFrame:
HLLM HXBX JHWO RPNZ ZHNL
2008-08-31 0 0 0 0 0
2008-09-30 0 0 0 0 0
2008-10-31 3 1 0 0 5
2008-11-30 0 -1 0 0 0
I am trying to replace all values that are NOT equal to 0 to the value 1
df = df.replace(df != 0, 1)
How can I rewrite this so that it works?
You can simply use
df[df != 0] = 1
HLLM HXBX JHWO RPNZ ZHNL
2008-08-31 0 0 0 0 0
2008-09-30 0 0 0 0 0
2008-10-31 1 1 0 0 1
2008-11-30 0 1 0 0 0
For the zero case, you can use the fact non-zero values are considered "Truthy":
df = df.astype(bool).astype(int)
For the general case, you can use pd.DataFrame.mask
:
df.mask(df.ne(0), 1, inplace=True)
print(df)
HLLM HXBX JHWO RPNZ ZHNL
2008-08-31 0 0 0 0 0
2008-09-30 0 0 0 0 0
2008-10-31 1 1 0 0 1
2008-11-30 0 1 0 0 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With