Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

DataFrame: Setting all the values to a particular columns as NaN

I have a DF like

A   B   C   D   E   F   G  H   I
=====================================
1   2   3       4   5   6   7   8
1   2   3       4   5   6   7   8
1   2   3       4   5   6   7   8

I need to set all the values for columns except for A and C to be Null

A   B   C   D   E   F   G  H   I
=====================================
1       3
1       3
1       3

If there a way to do this instead of using the below code like using a not condition to check for only columns A & C and set null to every other columns

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df[[‘B’,’D’,’E’,’F’,’G’,’H’,’I’]] = ”

>Solution :

An easy way could be to slice and reindex:

target = ['A', 'C']
out = df[target].reindex(df.columns, axis=1)

For in place modification you can take advantage of index difference:

df[df.columns.difference(target)] = float('nan')

output:

   A   B  C   D   E   F   G   H   I
0  1 NaN  3 NaN NaN NaN NaN NaN NaN
1  1 NaN  3 NaN NaN NaN NaN NaN NaN
2  1 NaN  3 NaN NaN NaN NaN NaN NaN

*NB. if you really want spaces as filling values:

# option 1:
out = df[target].reindex(df.columns, axis=1, fill_value='')

# option 2:
df[df.columns.difference(target)] = ''

# output:
   A B  C D E F G H I
0  1    3            
1  1    3            
2  1    3            
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading