Replace all column with 0 1 except date column

Viewed 26

I have a csv file containing of many columns. I want to change 0 1 2 into 0 1 and null. My code is working perfectly but there is an issue. I think it is also replacing 1 2 & 0 in date column too. I don't want this. Below is my code:

df1 = df.replace(to_replace = [0,1,2], value = [np.nan,0, 1])

The above code is replacing the given values in my df. I am using df1 in pivot_table, and when I check the output file it does not show the Date column. (Although I put the "Date" column in the index, inside pivot_table.). Can anybody help?

1 Answers

Use a dictionary:

df1 = df.replace({0:float('nan'), 1:0, 2:1})

To limit to given columns:

df1 = df.copy()
df.update(df[['col1', 'col2']].replace({0:float('nan'), 1:0, 2:1}))
Related