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
df[['B','D','E','F','G','H','I']] = ''
CodePudding user response:
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
CodePudding user response:
target = ['A', 'C']
columns = [column for column in df.columns if column not in target]
df[columns] = float('nan')