==== swap columns ====
$ ipython
Python 3.11.4 | packaged by Anaconda, Inc. | (main, Jul 5 2023, 13:47:18) [MSC v.1916 64 bit (AMD64)]
IPython 8.12.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]:
import pandas as pd
data = {'Spam': [0.0, 1.0],
'Ham' : [1.0, 0.0],
'PT1' : [0.11, 0.12],
'PT2' : [0.21, 0.22],
'PT3' : [0.31, 0.32],
'PT4' : [0.41, 0.42]}
df = pd.DataFrame(data)
df
Out[1]:
Spam Ham PT1 PT2 PT3 PT4
0 0.0 1.0 0.11 0.21 0.31 0.41
1 1.0 0.0 0.12 0.22 0.32 0.42
In [2]:
df[['PT2', 'PT1']] = df[['PT1', 'PT2']]
df
Out[2]:
Spam Ham PT1 PT2 PT3 PT4
0 0.0 1.0 0.21 0.11 0.31 0.41
1 1.0 0.0 0.22 0.12 0.32 0.42
In [3]:
pd.__version__
Out[3]:
'1.5.3'
Ref:-
* Got the sample data from https://stackoverflow.com/questions/57446160/swap-or-exchange-column-names-in-pandas-dataframe-with-multiple-columns and tweaked the data and column names a bit.
* https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#basics
* Says that the correct way to swap two columns is
df.loc[:, ['B', 'A']] = df[['A', 'B']].to_numpy()