Python - Sorting by absolute value without changing the data

Learn, how can we sort by absolute value without changing the data in Python pandas?
Submitted by Pranit Sharma, on August 23, 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.

Sorting refers to rearranging a series or a sequence in a particular fashion (ascending, descending, or in any specific pattern). Sorting in pandas DataFrame is required for effective analysis of the data.

Problem statement

Suppose we have a DataFrame with two columns A and B, we will find a simple way to sort this DataFrame by the absolute value of a particular column (let us say B), but without changing the actual data.

Sorting by absolute value without changing the data

The absolute value of any data (number) refers to the magnitude of that value, despite the fact whether it is positive or negative. We will use the abs() method to convert the actual value into absolute value and then we will use the sort_values() method to sort the values by absolute values. This method works on a particular column and it can sort the values either in ascending order or in descending order.

Let us understand with the help of an example,

Python program to sort by absolute value without changing the data

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'A':[10,20,30,40,50],
    'B':[-32,58,-11,20,-9]
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display Original DataFrame
print("Created DataFrame:\n",df,"\n")

# Sorting by abs values
result = df.reindex(df.B.abs().sort_values().index)

# Display result
print("Result:\n",result)

Output

The output of the above program is:

Example: Sorting by absolute value

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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