How To Change Order of Columns in Pandas Dataframe – With Examples

Pandas dataframe is a two-dimensional data structure that allows you to store data in rows and columns format. It allows you to store data of any scale and also allows easy data manipulation.

While using the dataframe for a machine learning program, you may need to change the order of columns in Dataframe to perform some data analysis operations.

You can change the order of columns in the pandas dataframe using the reindex() method.

In this tutorial, you’ll learn how to change the order of columns in a dataframe.

If You’re in Hurry…

You can use the below code snippet to change the order of columns of the dataframe using the reindex() method.

You can pass the columns list in the order you want. Then the dataframe columns will be reordered.

df = df.reindex(columns=['Available_Since_Date','Product_name', 'Unit_Price','No_Of_Units','Available_Quantity'])

df

When you execute the above code, the column Available_Since_date will be moved to the first position.

Dataframe Will Look Like

Available_Since_DateProduct_nameUnit_PriceNo_Of_UnitsAvailable_Quantity
011/5/2021Keyboard500.00055
14/23/2021Mouse200.00056
208/21/2021Monitor5000.2351010
309/18/2021CPU10000.55020Not Available
409/18/2021CPU10000.55020Not Available
501/05/2021Speakers250.5008NaT
6NaTNaTNaNNaTNaT

If You Want to Understand Details, Read on…

In this tutorial, you’ll learn the different methods available to reorder columns in the dataframe and also learn how to sort the columns of the dataframe alphabetically in ascending or descending order.

Sample Dataframe

Creating a sample dataframe that you’ll use throughout this tutorial.

Column Order

  1. Product_name
  2. Unit_Price
  3. No_Of_Units
  4. Available_Quantity
  5. Available_Since_Date

Snippet

import pandas as pd

data = {"Product_name":["Keyboard","Mouse", "Monitor", "CPU","CPU", "Speakers",pd.NaT],
        "Unit_Price":[500,200, 5000.235, 10000.550, 10000.550, 250.50,None],
        "No_Of_Units":[5,5, 10, 20, 20, 8,pd.NaT],
        "Available_Quantity":[5,6,10,"Not Available","Not Available", pd.NaT,pd.NaT],
        "Available_Since_Date":['11/5/2021', '4/23/2021', '08/21/2021','09/18/2021','09/18/2021','01/05/2021',pd.NaT]
       }

df = pd.DataFrame(data)

df

Dataframe Will Look Like

Product_nameUnit_PriceNo_Of_UnitsAvailable_QuantityAvailable_Since_Date
0Keyboard500.0005511/5/2021
1Mouse200.000564/23/2021
2Monitor5000.235101008/21/2021
3CPU10000.55020Not Available09/18/2021
4CPU10000.55020Not Available09/18/2021
5Speakers250.5008NaT01/05/2021
6NaTNaNNaTNaTNaT

Now let’s see the different methods available to reorder the columns.

Using Reindex

You can change the order of the dataframe columns using the reindex() method.

The reindex() method accepts columns as a list.

Pass the columns as list in the order of how you want to rearrange them.

Snippet

df = df.reindex(columns=['Available_Since_Date','Product_name', 'Unit_Price','No_Of_Units','Available_Quantity'])

df

When you execute the above code, the column Available_Since_Date is moved to the first position. As in the order you’ve specified for the columns attribute.

Dataframe Will Look Like

Available_Since_DateProduct_nameUnit_PriceNo_Of_UnitsAvailable_Quantity
011/5/2021Keyboard500.00055
14/23/2021Mouse200.00056
208/21/2021Monitor5000.2351010
309/18/2021CPU10000.55020Not Available
409/18/2021CPU10000.55020Not Available
501/05/2021Speakers250.5008NaT
6NaTNaTNaNNaTNaT

Using List of Columns Names

You can use a list of column names also and pass that list to the reindex() method as shown below.

Snippet

column_names = ['Available_Since_Date','Product_name', 'Unit_Price','No_Of_Units','Available_Quantity']

df = df.reindex(columns=column_names)

df

Now also the columns are arranged as the order passed in the list.

Dataframe Will Look Like

Available_Since_DateProduct_nameUnit_PriceNo_Of_UnitsAvailable_Quantity
011/5/2021Keyboard500.00055
14/23/2021Mouse200.00056
208/21/2021Monitor5000.2351010
309/18/2021CPU10000.55020Not Available
409/18/2021CPU10000.55020Not Available
501/05/2021Speakers250.5008NaT
6NaTNaTNaNNaTNaT

Using Dataframe Indexing

You can use the dataframe indexing using the column names and create a new dataframe out of it to rearrange the columns.

Snippet

df = df[['Available_Since_Date','Product_name', 'Unit_Price','No_Of_Units','Available_Quantity']]

df

When you execute the above snippet, the dataframe columns will be rearranged to the order passed for the dataframe indexing.

Dataframe Will Look Like

Available_Since_DateProduct_nameUnit_PriceNo_Of_UnitsAvailable_Quantity
011/5/2021Keyboard500.00055
14/23/2021Mouse200.00056
208/21/2021Monitor5000.2351010
309/18/2021CPU10000.55020Not Available
409/18/2021CPU10000.55020Not Available
501/05/2021Speakers250.5008NaT
6NaTNaTNaNNaTNaT

This is how you can rearrange columns using dataframe indexing.

Sorting Columns Alphabetically

In this section, you’ll learn how to sort columns of the dataframe alphabetically using reindex() and sort_index().

Using Reindex()

You can sort the columns of the dataframe using the reindex() method and sorted() method.

  1. Fetch the existing columns for the dataframe using df.columns
  2. Pass it to the sorted() method. It’ll sort the methods alphabetically
  3. Pass the sorted value to the reindex() method
  4. Specify axis=1 to denote that the column axes needs to be reordered
df = df.reindex(sorted(df.columns), axis=1)

df

Now the dataframe columns will be sorted alphabetically as below.

Dataframe Will Look Like

Available_QuantityAvailable_Since_DateNo_Of_UnitsProduct_nameUnit_Price
0511/5/20215Keyboard500.000
164/23/20215Mouse200.000
21008/21/202110Monitor5000.235
3Not Available09/18/202120CPU10000.550
4Not Available09/18/202120CPU10000.550
5NaT01/05/20218Speakers250.500
6NaTNaTNaTNaTNaN

Using Sort_Index()

You can sort the columns of the dataframe using the sort_index() method. Sort_index is typically used to sort the index column. Either the row index or the column index.

To sort the column index, you need to pass axis=1 to denote that the column axes are to be renamed.

Snippet

df = df.sort_index(axis=1)

df

When you execute the above code, the columns of the dataframe will be sorted alphabetically as shown below.

Dataframe Will Look Like

Available_QuantityAvailable_Since_DateNo_Of_UnitsProduct_nameUnit_Price
0511/5/20215Keyboard500.000
164/23/20215Mouse200.000
21008/21/202110Monitor5000.235
3Not Available09/18/202120CPU10000.550
4Not Available09/18/202120CPU10000.550
5NaT01/05/20218Speakers250.500
6NaTNaTNaTNaTNaN

This is how you can sort columns using the sort_index() alphabetical order.

Sorting Columns in Descending order

You can sort the columns in a descending alphabetical order using the sort_index() method.

Parameters

  • axis=1 – To denote that column axes must be reordered
  • ascending=False – To denote that the columns must be sorted in a descending order.

Snippet

df2 = df.sort_index(axis=1, ascending=False)

df2

When you execute the above code, you’ll see the columns of the dataframe are sorted in descending alphabetical order.

Dataframe Will Look Like

Unit_PriceProduct_nameNo_Of_UnitsAvailable_Since_DateAvailable_Quantity
0500.000Keyboard511/5/20215
1200.000Mouse54/23/20216
25000.235Monitor1008/21/202110
310000.550CPU2009/18/2021Not Available
410000.550CPU2009/18/2021Not Available
5250.500Speakers801/05/2021NaT
6NaNNaTNaTNaTNaT

This is how you can use reindex() and sort_index() methods to change the order of the dataframe.

Move Column to First Position

In this section, you’ll learn how to move a column to the first position.

There are no methods directly available to move a column to the first position.

  1. Pop out the column to be moved using the pop() method
  2. Insert the column into the 0th position using the insert() method.

This will move the column to the front position.

Snippet

column_to_reorder = df.pop('Unit_Price')

df.insert(0, 'Unit_Price', column_to_reorder)

df

By executing the above snippet, the column Unit_Price Column is shifted to the first position.

Dataframe Will Look Like

Unit_PriceProduct_nameNo_Of_UnitsAvailable_Since_DateAvailable_Quantity
0500.000Keyboard511/5/20215
1200.000Mouse54/23/20216
25000.235Monitor1008/21/202110
310000.550CPU2009/18/2021Not Available
410000.550CPU2009/18/2021Not Available
5250.500Speakers801/05/2021NaT
6NaNNaTNaTNaTNaT

Move Column to Last Position

As similar to moving a column to the first position, there are no methods directly available to move a column to the last position.

  1. Pop out the column to be moved using the pop() method
  2. Find the length of the dataframe column using len(df. columns). Since position is 0 based, you can use the length to insert into the last position.
  3. Insert the column into the len(df. columns) position using the insert() method.

This will move the column to the end position.

Snippet

column_to_reorder = df.pop('Unit_Price')

df.insert(len(df. columns), 'Unit_Price', column_to_reorder)

df

By executing the above snippet, the column Unit_Price Column is shifted to the last position.

Dataframe Will Look Like

Product_nameNo_Of_UnitsAvailable_Since_DateAvailable_QuantityUnit_Price
0Keyboard511/5/20215500.000
1Mouse54/23/20216200.000
2Monitor1008/21/2021105000.235
3CPU2009/18/2021Not Available10000.550
4CPU2009/18/2021Not Available10000.550
5Speakers801/05/2021NaT250.500
6NaTNaTNaTNaTNaN

Move Column To Specific Position

You can move the column to a specific position by popping out the column and inserting it into the specific position.

  1. Define the position to which the column needs to be moved
  2. Pop out the column to be moved using the pop() method
  3. Insert the popped up column to the defined position using the insert() method.

Snippet

position =2

column_to_reorder = df.pop('Unit_Price')

df.insert(position, 'Unit_Price', column_to_reorder)

df

By executing the above snippet, the column Unit_Price Column is shifted to the 3rd position. Because the index is 0 based while using the insert() method.

Dataframe Will Look Like

Product_nameNo_Of_UnitsUnit_PriceAvailable_Since_DateAvailable_Quantity
0Keyboard5500.00011/5/20215
1Mouse5200.0004/23/20216
2Monitor105000.23508/21/202110
3CPU2010000.55009/18/2021Not Available
4CPU2010000.55009/18/2021Not Available
5Speakers8250.50001/05/2021NaT
6NaTNaTNaNNaTNaT

This is how you can move columns to either first, last, or a specified position.

Change Order Like Other DataFrame

Until now, you’ve learned how to reorder the columns in the same dataframe using the same dataframe columns.

If you want to reindex columns of a dataframe similar to the order of the dataframe, you can use the method reindex_like() method.

It’ll reorder the columns based on the order of the columns in the dataframe passed.

Snippet

df = df.reindex_like(df2)

df

When executing the above snippet, the columns in the dataframe df will be reordered similar to the order of columns in dataframe df2.

Dataframe Will Look Like

Unit_PriceProduct_nameNo_Of_UnitsAvailable_Since_DateAvailable_Quantity
0500.000Keyboard511/5/20215
1200.000Mouse54/23/20216
25000.235Monitor1008/21/202110
310000.550CPU2009/18/2021Not Available
410000.550CPU2009/18/2021Not Available
5250.500Speakers801/05/2021NaT
6NaNNaTNaTNaTNaT

This is how you can rename the columns of a dataframe based on the order of the columns from the other dataframe.

Conclusion

To summarize, You’ve learned how to change the order of the dataframe columns using the reindex() method and also using the dataframe indexing.

You’ve also learned to sort the columns alphabetically in ascending or descending order using reindex() or sort_index() methods.

Also, you’ve learned how to move the column to the first position, last position, or to a specific position.

All these operations can be used when you want to perform various data manipulation operations in the pandas dataframe.

If you have any questions, comment below.

You May Also Like

Leave a Comment