Python change column order

Change Order of Columns of a Pandas DataFrame

During the data preprocessing and feature creation stage, it might happen that you end up with columns that may not necessarily be in the order that you’d like. In this tutorial, we’ll look at how to change the order of columns of a pandas dataframe.

How to reorder columns of a pandas dataframe?

To change the order of columns of a dataframe, you can pass a list with columns in the desired order to [] (that is, indexing with [] ). The following is the syntax:

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

df_correct_order = df[[col1, col2, col3, . coln]]

Generally, we use [] in Pandas dataframes to subset a dataframe but it can also be used to reorder the columns. You can also use .loc and .iloc to change the order of columns of a dataframe.

Examples

First, let’s create a dataframe that we’ll be using throughout this tutorial.

import pandas as pd data = < 'Name': ['Microsoft Corporation', 'Google, LLC', 'Tesla, Inc.',\ 'Apple Inc.', 'Netflix, Inc.'], 'Shares': [100, 50, 150, 200, 80], 'Symbol': ['MSFT', 'GOOG', 'TSLA', 'AAPL', 'NFLX'] ># create dataframe df = pd.DataFrame(data) # display the dataframe df

Pandas dataframe with 5 rows and 3 columns containing information on a stock portfolio.

Here, df is a dataframe of a sample stock portfolio with columns Name , Shares , Symbol . We want to reorder the columns such that the resulting dataframe has columns in the order Name , Symbol , Shares . Let’s see examples of some of the ways we can achieve this.

1. Change column order using []

As mentioned above, you can pass the columns in the order you like as a list.

# new dataframe with different column order df_new = df[['Name', 'Symbol', 'Shares']] # display the dataframe df_new

pandas dataframe after changing column order

In the above example, we change the order of columns from Name , Shares , Symbol to Name , Symbol , Shares .

2. Change column order using .loc

You can also reorder a pandas dataframe by indexing it using .loc. This way, you can reorder columns using their names as we did in the previous example.

# new dataframe with different column order df_new = df.loc[:, ['Name', 'Symbol', 'Shares']] # display the dataframe df_new

pandas dataframe after changing column order

In the above example, we change the order of columns from Name , Shares , Symbol in the original dataframe df to Name , Symbol , Shares in the returned dataframe df_new using the dataframe’s .loc property.

Читайте также:  Java arraylist example with objects

3. Change column order using .iloc

You can also change the column order of a dataframe by indexing it using .iloc . Here, we pass the column indexes instead of their names in the order that we want.

# new dataframe with different column order df_new = df.iloc[:, [0, 2, 1]] # display the dataframe df_new

pandas dataframe after changing column order

In the above example, we reorder columns from the original dataframe df using their indexes rather than their names. The resulting dataframe is saved as df_new . The columns in the dataframe df_new are ordered Name , Symbol , Shares .

For more, refer to pandas’ official guide on indexing and selecting data.

With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having pandas version 1.0.5

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

  • Pandas – Sort a DataFrame
  • Change Order of Columns of a Pandas DataFrame
  • Pandas DataFrame to a List in Python
  • Pandas – Count of Unique Values in Each Column
  • Pandas – Replace Values in a DataFrame
  • Pandas – Filter DataFrame for multiple conditions
  • Pandas – Random Sample of Rows
  • Pandas – Random Sample of Columns
  • Save Pandas DataFrame to a CSV file
  • Pandas – Save DataFrame to an Excel file
  • Create a Pandas DataFrame from Dictionary
  • Convert Pandas DataFrame to a Dictionary
  • Drop Duplicates from a Pandas DataFrame
  • Concat DataFrames in Pandas
  • Append Rows to a Pandas DataFrame
  • Compare Two DataFrames for Equality in Pandas
  • Get Column Names as List in Pandas DataFrame
  • Select One or More Columns in Pandas
  • Pandas – Rename Column Names
  • Pandas – Drop one or more Columns from a Dataframe
  • Pandas – Iterate over Rows of a Dataframe
  • How to Reset Index of a Pandas DataFrame?
  • Read CSV files using Pandas – With Examples
  • Apply a Function to a Pandas DataFrame

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

4 Ways to Change the Column Order of a Pandas Dataframe in Python

Python Change The Column Order Of A Pandas DataFrame

In this tutorial, we are going to discuss how we can change the column order of a given pandas DataFrame object. During the data preprocessing stage, we might encounter a situation where the columns of the concerned pandas DataFrame are not in the desired order then we have to change the column order of the DataFrame.

How to change the column order of a Pandas Dataframe?

Let’s get right into the different methods to change the column order of a dataframe in Pandas.

Method 1: Using the desired order columns list

This is one of the simplest methods to change the order of the columns of a pandas DataFrame object. In this method, we simply pass the Python list of columns of the DataFrame in the desired order to the DataFrame object. Let’s see how to code this method in Python.

# Method-1 # Import pandas Python module import pandas as pd # Create a pandas DataFrame df = pd.DataFrame() print('Given pandas DataFrame:\n') print(df) # Change the order of the DataFrame # Using the desired order columns list df_1 = df[['Name', 'CGPA', 'Roll', 'Branch']] print('\nPandas DataFrame with changed column order:\n') print(df_1)
Given pandas DataFrame: Roll Name Branch CGPA 0 111 Sanjay ECE 8.15 1 112 Aman ICE 9.03 2 113 Ankit IT 7.85 3 114 Ravi CSE 8.55 4 115 Komal CHE 9.45 Pandas DataFrame with changed column order: Name CGPA Roll Branch 0 Sanjay 8.15 111 ECE 1 Aman 9.03 112 ICE 2 Ankit 7.85 113 IT 3 Ravi 8.55 114 CSE 4 Komal 9.45 115 CHE

Method 2: Using the loc method

In this method, we will make use of the loc method of the pandas DataFrame class. Using the loc method, we can reorder the columns of the pandas DataFrame object by providing a Python list of column names. Let’s write the Python code to implement this method.

# Method-2 # Import pandas Python module import pandas as pd # Create a pandas DataFrame df = pd.DataFrame() print('Given pandas DataFrame:\n') print(df) # Change the order of the DataFrame # Using the loc method of pandas DataFrame class df_2 = df.loc[2:4, ['Roll', 'Name', 'CGPA', 'Branch']] print('\nPandas DataFrame with changed column order:\n') print(df_2)
Given pandas DataFrame: Name Roll Branch CGPA 0 Sanjay 111 ECE 8.15 1 Aman 112 ICE 9.03 2 Ankit 113 IT 7.85 3 Ravi 114 CSE 8.55 4 Komal 115 CHE 9.45 Pandas DataFrame with changed column order: Roll Name CGPA Branch 2 113 Ankit 7.85 IT 3 114 Ravi 8.55 CSE 4 115 Komal 9.45 CHE

Method 3: Using the iloc method

In this method, we will be using the iloc method of the pandas DataFrame class. Using the iloc method, we can reorder the columns of the pandas DataFrame object by providing a Python list of column indices (i.e. 0, 1, 2, 3, …) instead of the column names. Let’s see how to implement this method through Python code.

# Method-3 # Import pandas Python module import pandas as pd # Create a pandas DataFrame df = pd.DataFrame() print('Given pandas DataFrame:\n') print(df) # Change the order of the DataFrame # Using the iloc method of pandas DataFrame class df_3 = df.iloc[1:4, [1, 2, 0, 3]] print('\nPandas DataFrame with changed column order:\n') print(df_3)
Given pandas DataFrame: CGPA Name Roll Branch 0 8.15 Sanjay 111 ECE 1 9.03 Aman 112 ICE 2 7.85 Ankit 113 IT 3 8.55 Ravi 114 CSE 4 9.45 Komal 115 CHE Pandas DataFrame with changed column order: Name Roll CGPA Branch 1 Aman 112 9.03 ICE 2 Ankit 113 7.85 IT 3 Ravi 114 8.55 CSE

NOTE: In the above two methods loc and iloc , we have an added advantage of selecting only a range of rows in the given pandas DataFrame object.

Читайте также:  Python pip install uwsgi

Method 4: Using the reindex() function

In this method, we will be using the reindex() function of the pandas DataFrame object. Using the reindex() function, we can rearrange the columns order of the pandas DataFrame object by passing a Python list of column names. Let’s implement this method through Python code.

# Method-4 # Import pandas Python module import pandas as pd # Create a pandas DataFrame df = pd.DataFrame() print('Given pandas DataFrame:\n') print(df) # Change the order of the DataFrame # Using the reindex() function of pandas DataFrame class df_4 = df.reindex(columns = ['Roll', 'CGPA', 'Name', 'Branch']) print('\nPandas DataFrame with changed column order:\n') print(df_4)
Given pandas DataFrame: Branch CGPA Name Roll 0 ECE 8.15 Sanjay 111 1 ICE 9.03 Aman 112 2 IT 7.85 Ankit 113 3 CSE 8.55 Ravi 114 4 CHE 9.45 Komal 115 Pandas DataFrame with changed column order: Roll CGPA Name Branch 0 111 8.15 Sanjay ECE 1 112 9.03 Aman ICE 2 113 7.85 Ankit IT 3 114 8.55 Ravi CSE 4 115 9.45 Komal CHE

Summing-up

In this tutorial, we have learned how the four different ways to change the order of the columns of a pandas DataFrame object. Hope you have understood all the methods discussed above and are excited to use them on your own. Thanks for reading and stay tuned with us for more such amazing content on Python programming.

Источник

How to change Order of Columns in Pandas DataFrame?

You can change the order of columns in a DataFrame by using DataFrame.reindex(), DataFrame indexing technique, or DataFrame constructor.

1. Change order of columns using DataFrame.reindex()

You can change the order of columns by calling DataFrame.reindex() on the original dataframe with rearranged column list as argument.

new_dataframe = dataframe.reindex(columns=['a', 'c', 'b'])

The reindex() function returns a new DataFrame with the given order of columns.

Читайте также:  Php fpm performance tuning

In the following program, we will take a DataFrame with columns a, b, c and change the order of columns to a, c, b.

Python Program

import pandas as pd #initialize a dataframe df = pd.DataFrame( [[21, 72, 67], [23, 78, 62], [32, 74, 54], [52, 54, 76]], columns=['a', 'b', 'c']) #change order of columns df_new = df.reindex(columns=['a', 'c', 'b']) #print new dataframe print(df_new)
 a c b 0 21 67 72 1 23 62 78 2 32 54 74 3 52 76 54

2. Change order of columns using DataFrame Indexing

DataFrame indexing can be used change the order of columns in a given DataFrame.

Following is the syntax to use DataFrame indexing.

new_dataframe = dataframe[['a', 'c', 'b']]

In the following program, we will take a DataFrame with columns a, b, c and change the order of columns to a, c, b.

Python Program

import pandas as pd #initialize a dataframe df = pd.DataFrame( [[21, 72, 67], [23, 78, 62], [32, 74, 54], [52, 54, 76]], columns=['a', 'b', 'c']) #change order of columns df_new = df[['a', 'c', 'b']] #print new dataframe print(df_new)
 a c b 0 21 67 72 1 23 62 78 2 32 54 74 3 52 76 54

3. Change order of columns using DataFrame Constructor

You can also use DataFrame Constructor to rearrange the order of columns. Consider the existing DataFrame as raw data, and create a new DataFrame, with this raw data and desired order of columns.

Following is the syntax to create a DataFrame with updated column order.

new_dataframe = pd.dataframe(raw_data, index=['a', 'c', 'b'])

In the following program, we will take a DataFrame with columns a, b, c and change the order of columns to a, c, b.

Python Program

import pandas as pd #initialize a dataframe df = pd.DataFrame( [[21, 72, 67], [23, 78, 62], [32, 74, 54], [52, 54, 76]], columns=['a', 'b', 'c']) #change order of columns df_new = pd.DataFrame(df, columns=['a', 'c', 'b']) #print new dataframe print(df_new)
 a c b 0 21 67 72 1 23 62 78 2 32 54 74 3 52 76 54

Summary

In this Python Tutorial, we learned how to change the order of columns in DataFrame.

Источник

Оцените статью