In MATLAB, to swap the first and second columns of a table A, one would do this1
A = A(:, [2 1 3:end]);
Is there a similarly convenient way to do this if A were a pandas DataFrame instead?
1 MATLAB uses 1-based indexing.
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
import pandas as pd
df = pd.read_csv('/Users/parent/Desktop/Col_swap.csv')
print(df)
columns_titles = ["A","B","C","E"]
df_reorder=df.reindex(columns=columns_titles)
df_reorder.to_csv('/Users/parent/Desktop/col_reorder1.csv', index=False)
print(df_reorder)
Output:
B A C E
0 c1 a1 b1 d1
1 c2 a2 b2 d2
A B C E
0 a1 c1 b1 d1
1 a2 c2 b2 d2