How to switch column values in the same Pandas DataFrame

Viewed 175

I have the following DataFrame:

enter image description here

I need to switch values of col2 and col3 with the values of col4 and col5. Values of col1 will remain the same. The end result needs to look as the following:

enter image description here

Is there a way to do this without looping through the DataFrame?

4 Answers

This should do:

og_cols = df.columns
new_cols = [df.columns[0], *df.columns[3:], *df.columns[1:3]]
df = df[new_cols] # Sort columns in the desired order
df.columns = og_cols # Use original column names

Use rename in pandas

In [160]: df = pd.DataFrame({'A':[1,2,3],'B':[3,4,5]})

In [161]: df
Out[161]:
   A  B
0  1  3
1  2  4
2  3  5

In [167]: df.rename({'B':'A','A':'B'},axis=1)
Out[167]:
   B  A
0  1  3
1  2  4
2  3  5

If you want to swap the column values:

df.iloc[:, 1:3], df.iloc[:, 3:] = df.iloc[:,3:].to_numpy(copy=True), df.iloc[:,1:3].to_numpy(copy=True)

Pandas reindex could help :

cols = df.columns

#reposition the columns
df = df.reindex(columns=['col1','col4','col5','col2','col3'])
#pass in new names
df.columns = cols
Related