How to find local max and min in pandas?

Learn, how to find local max and min in Python Pandas?
Submitted by Pranit Sharma, on February 18, 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.

Problem statement

Suppose that we are given a pandas DataFrame with a column. We need to create two more columns for max and min for the data of this column respectively. we need to fill these columns with nan values except where there is local maxima or local minima.

Finding local max and min in pandas

For this purpose, if we assume that our column values are a labeled data set, we can find the local peaks by using the shift() operation.

Let us understand with the help of an example,

Python program to find local max and min in pandas

# Import numpy
import numpy as np

# Import pandas
import pandas as pd

# Creating a DataFrame
np.random.seed(0)
rs = np.random.randn(20)
xs = [0]
for r in rs:
    xs.append(xs[-1]*0.9 + r)
df = pd.DataFrame(xs, columns=['data'])

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

# Find local maxima and minima

df['min'] = df.data[(df.data.shift(1) > df.data) & (df.data.shift(-1) > df.data)]
df['max'] = df.data[(df.data.shift(1) < df.data) & (df.data.shift(-1) < df.data)]

# Display modified DataFrame
print("Modified DataFrame:\n",df,"\n")

Output

The output of the above program is:

Example: How to find local max and min in pandas?

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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