Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing 0's with 1's in a data frame

Tags:

python-3.x

I have a data frame df which has columns A,B,C,D,...,X,Y,Z and I wish to replace all 0 entries with 1 in all but columns C and D.

The following code that I am have attempted is:

df[df.columns[~df.columns.isin(['C','D'])]].replace(0,1,inplace=True)

but it is not working.

New to coding so any help here would be greatly appreciated!

like image 419
Hugh Entwistle Avatar asked Jan 18 '26 16:01

Hugh Entwistle


1 Answers

I have a data frame df which has columns A,B,C,D,...,X,Y,Z and I wish to replace all 0 entries with 1 in all but columns C and D.

# Save the columns
c = df['C']
d = df['D']

# Remove the columns
df.drop('C', axis=1, inplace=True)
df.drop('D', axis1=, inplace=True)

# Make your replacement
df.replace(0, 1)

# Replace the columns
df['C'] = c
df['D'] = d
like image 57
artemis Avatar answered Jan 21 '26 09:01

artemis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!