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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With