Issue
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.
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.