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?
Submitted by Pranit Sharma, on November 14, 2022

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.

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

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).

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.

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.

Let us understand with the help of an example,

Python code 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:

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

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.