I'm having a pandas DataFrame like following.
3,0,1,0,0
11,0,0,0,0
1,0,0,0,0
0,0,0,0,4
13,1,1,5,0
I need to replace every other value to '1' except '0'. So my expected output.
1,0,1,0,0
1,0,0,0,0
1,0,0,0,0
0,0,0,0,1
1,1,1,1,0
Just use something like df[df != 0]
to get at the nonzero parts of your dataframe:
import pandas as pd
import numpy as np
np.random.seed(123)
df = pd.DataFrame(np.random.randint(0, 10, (5, 5)), columns=list('abcde'))
df
Out[11]:
a b c d e
0 2 2 6 1 3
1 9 6 1 0 1
2 9 0 0 9 3
3 4 0 0 4 1
4 7 3 2 4 7
df[df != 0] = 1
df
Out[13]:
a b c d e
0 1 1 1 1 1
1 1 1 1 0 1
2 1 0 0 1 1
3 1 0 0 1 1
4 1 1 1 1 1
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