How to swap two DataFrame columns?
pandas has reindex method that does it. You just need to give a list with the column names in the order you wish:
columns_titles = ["B","A"]
df=df.reindex(columns=columns_titles)
Cheers
A slight variant on acushner's answer:
# get a list of the columns
col_list = list(df)
# use this handy way to swap the elements
col_list[0], col_list[1] = col_list[1], col_list[0]
# assign back, the order will now be swapped
df.columns = col_list
example:
In [39]:
df = pd.DataFrame({'a':randn(3), 'b':randn(3), 'c':randn(3)})
df
Out[39]:
a b c
0 -0.682446 -0.200654 -1.609470
1 -1.998113 0.806378 1.252384
2 -0.250359 3.774708 1.100771
In [40]:
col_list = list(df)
col_list[0], col_list[1] = col_list[1], col_list[0]
df.columns = col_list
df
Out[40]:
b a c
0 -0.682446 -0.200654 -1.609470
1 -1.998113 0.806378 1.252384
2 -0.250359 3.774708 1.100771
UPDATE
If you just want to change the column order without changing the column contents then you can reindex using fancy indexing:
In [34]:
cols = list(df)
cols[1], cols[0] = cols[0], cols[1]
cols
Out[34]:
['b', 'a', 'c']
In [35]:
df.ix[:,cols]
Out[35]:
b a c
0 -0.200654 -0.682446 -1.609470
1 0.806378 -1.998113 1.252384
2 3.774708 -0.250359 1.100771
c = A.columns
A = A[c[np.r_[1, 0, 2:len(c)]]]
or, even easier:
A[[c[0], c[1]]] = A[[c[1], c[0]]]
*edit: fixed per Ivan's suggestions.