How to drop columns, do operation on remaining columns, then insert back the dropped columns?

Viewed 27

I have a large dataset. I want to apply something on all the columns except for 2.

I dropped the 2 columns and created a separate dataframe, then tried merging the dataframes after the operation is applied.

I tried appending, merging, joining the two dataframes but they all created duplicate rows. Appending doubled the row count, and changed the dropped columns.

I just want to add back the 2 columns to the initial dataframe unchanged. Any help?

df= col1 col2 col3... col100
     1    2   3         100

df2=df.loc[:,['col2', 'col3']]
df.drop(columns=['col2', 'col3'], inplace=True)

Then do what I needed to do to df.

Now I want to merge df and df2.

1 Answers

Like this:

cols = ['col2', 'col3']
df2 = df[cols]
df.drop(columns=cols, inplace=True)
# do something
df = pd.concat([df, df2], axis=1)

This will work as long as you didn't remove rows from either dataframes or changed their order

Related