Swap columns in dataframe in Pandas doesn't work

Question:

        def columnchange (df_old, a=None, b=None):
             x=df_old[a]
             df_old[a]=df_old[b]
             df_old[b]=x
             return df_old

I am wondering why this column swapping is not working. It makes both the columns of the df_old equal. An explanation for this would be helpful. I am able to swap the columns using column index though. But don’t know why this is not working.

Asked By: XSCD

||

Answers:

Alternative I – as per documentation

df.loc[:, ['b', 'a']] = df[['a', 'b']].to_numpy()

Alternative II

The reason is that you don’t create copies, you create references.

try this:

    def columnchange (df_old, a=None, b=None):
         x=df_old[a].copy()
         df_old[a]=df_old[b].copy()
         df_old[b]=x
         return df_old

Further explaination:

x = df_old[a]

means you could do x = x + 1 and the result will be in df_old[a] as well. Because you created a reference, or lets say a "synonym" of the series, not a copy.

Answered By: Andreas
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.