Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas replace all numeric values not equal to a specific value

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?

like image 274
user3062459 Avatar asked Dec 18 '22 20:12

user3062459


2 Answers

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
like image 175
Cleb Avatar answered May 13 '23 13:05

Cleb


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
like image 24
jpp Avatar answered May 13 '23 13:05

jpp