2

I have a pandas dataframe df with this contents;

Column1   Column2    Column3  
C11         C21        C31
C12         C22        C32
C13         C23        C33

I would like to swap the contents between Column 1 and Column 2.

The output dataframe should look like this;

Column1   Column2    Column3  
C21         C11        C31
C22         C12        C32
C23         C13        C33

I am using python v3.6

user3848207
  • 3,737
  • 17
  • 59
  • 104

1 Answers1

4

I'm sure there's a better answer, but you can swap the column names and then reorder:

df = pd.DataFrame({"Column1": ["C11", "C12", "C13"],
                   "Column2": ["C21", "C22", "C23"],
                   "Column3": ["C31", "C32", "C33"]})
df.columns = ["Column2", "Column1", "Column3"]
df[["Column1", "Column2", "Column3"]]
ZaxR
  • 4,896
  • 4
  • 23
  • 42
  • This is a nice way to tackle it. Although you can make use of a function etc. eg `df.rename(lambda x: x.translate(x.maketrans('12','21')),axis=1).iloc[:,[1,0,2]]` – Onyambu Aug 31 '18 at 03:04