Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap two DataFrame columns?

Tags:

python

pandas

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.

like image 445
kjo Avatar asked Sep 03 '14 16:09

kjo


People also ask

How do you swap rows and columns in a DataFrame?

Use the T attribute or the transpose() method to swap (= transpose) the rows and columns of DataFrame. Neither method changes an original object but returns the new object with the rows and columns swapped (= transposed object).


1 Answers

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

like image 80
aspire57 Avatar answered Oct 14 '22 08:10

aspire57