Order columns of a pandas dataframe according to the values in a row

Learn, how to order columns of a pandas dataframe according to the values in a row in Python? By Pranit Sharma Last updated : October 05, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Columns are the different fields that contain their particular values when we create a DataFrame. We can perform certain operations on both row & column values.

Problem statement

Suppose, we are given a DataFrame or we are creating a DataFrame with some specified columns in a particular order. Now after analyzing the DataFrame, we need to change the order of the columns on the basis of some row values (let us say the last row).

Ordering columns of a dataframe according to the values in a row

For this purpose, we need to play with the columns of the DataFrame, we need to find the last_valid_index() values which will return a non-null value from the end of the columns and we will pass these values inside pandas.DataFrame.ix() method with pandas.DataFrame.columns() and on this result, we will apply argsort() method to order these values.

Let us understand with the help of an example,

Python program to order columns of a pandas dataframe according to the values in a row

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating DataFrame
df = pd.DataFrame(np.random.randn(10, 4), columns=['A', 'B', 'C', 'D'])

# Display dataframe
print('Original DataFrame:\n',df,'\n')

# New column ordering
new_columns = df.columns[df.ix[df.last_valid_index()].argsort()]

# # Fixing new columns
res = df[new_columns]

# Display new DataFrame
print("New DataFrame:\n",res,"\n")

Output

The output of the above program is:

Example: Order columns of a pandas dataframe according to the values in a row

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.