Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas DataFrame Replace every value by 1 except 0

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
like image 796
Nilani Algiriyage Avatar asked Sep 05 '25 03:09

Nilani Algiriyage


1 Answers

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
like image 177
Marius Avatar answered Sep 07 '25 19:09

Marius