How to reverse the column order of the Pandas DataFrame?

How to reverse the column order of the Pandas DataFrame?

You can reverse the column order of a pandas DataFrame by simply selecting the columns in the reverse order. Here's how you can do it:

Let's start by creating a sample DataFrame:

import pandas as pd data = { 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] } df = pd.DataFrame(data) print(df) 

Output:

 A B C 0 1 4 7 1 2 5 8 2 3 6 9 

To reverse the column order:

df = df[df.columns[::-1]] print(df) 

Output:

 C B A 0 7 4 1 1 8 5 2 2 9 6 3 

Here, we used df.columns[::-1] to reverse the order of the column labels, and then we selected the columns from the DataFrame in that reversed order.


More Tags

rolling-sum ruby-on-rails colorama importerror java-io splunk-query last-modified positioning slider smooth-scrolling

More Programming Guides

Other Guides

More Programming Examples