Osca
Osca

Reputation: 1694

replace all non zero numbers in certain dataframe columns with 1

I want to change all none-zero integers in the dataframe to 1

the data enter image description here

I tried data.iloc[, 2:]!= 0 and received boolean values as result. How can I replace all non-zero values to 1 ?

Upvotes: 0

Views: 284

Answers (1)

jezrael
jezrael

Reputation: 862511

Use DataFrame.mask:

data.iloc[, 2:] = data.iloc[, 2:].mask(data.iloc[, 2:]!= 0, 1)

Or if exist only positive values use DataFrame.clip:

data.iloc[, 2:] = data.iloc[, 2:].clip(upper=1)

Upvotes: 1

Related Questions