0

I want to change the existing dataframe value to nan. What is the way to do it when you need to change several?

dataframe['A', 'B'....] = np.nan

I tried this but nothing changed

kwsong0314
  • 221
  • 4
  • 11
  • Post a sample dataframe and desired output. Also include what have you tried. – Amit Vikram Singh Apr 09 '21 at 09:39
  • try double brackets dataframe[['A', 'B'....]] = np.nan – Jayvee Apr 09 '21 at 09:49
  • Does this answer your question? [How to add multiple columns to pandas dataframe in one assignment?](https://stackoverflow.com/questions/39050539/how-to-add-multiple-columns-to-pandas-dataframe-in-one-assignment) – 576i Apr 09 '21 at 09:50

1 Answers1

0

Double brackets are required in this case, to pass the list of columns to the dataframe index operator []. For the OP case would be:

dataframe[['A', 'B'....]] = np.nan 

Reproducible example:

import numpy as np
import pandas as pd   

dict= {'ColA':[1,2,3], 'ColB':[4,5,6], 'ColC':[7,8,9], 'ColD':[-1,-2,-3] }    
    
df=pd.DataFrame(dict,index=['I1','I2','I3'])    
print(df) 

df[['ColA','ColD']]=np.nan
print(df)

Note: This solution was originally suggested via comment, now included as an answer with a reproducible example for future reference.

Jayvee
  • 10,670
  • 3
  • 29
  • 40