Home >Backend Development >Python Tutorial >How Do I Filter DataFrame Rows Based on a Value Range in Pandas?

How Do I Filter DataFrame Rows Based on a Value Range in Pandas?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-14 14:43:02826browse

How Do I Filter DataFrame Rows Based on a Value Range in Pandas?

Filtering DataFrame Rows by Value Range

When manipulating dataframes, it's often necessary to select rows based on specific criteria. One such scenario is selecting rows within a specified value range. While using loops can achieve this, a more efficient and vectorized approach is preferred.

In the given code:

df = df[99 <= df['closing_price'] <= 101]

An error occurs due to ambiguous truth values in the comparison. To remedy this, use the between() method from the Pandas Series class:

Solution:

df = df[df['closing_price'].between(99, 101)]

The between() method takes two values as parameters, representing the lower and upper bounds of the range. It returns a Boolean Series with True for rows that meet the criteria and False otherwise. This Series can then be used to filter the dataframe to include only the desired rows.

This vectorized solution avoids the use of loops, enhancing performance and conciseness. Moreover, it is more intuitive to read and maintain.

The above is the detailed content of How Do I Filter DataFrame Rows Based on a Value Range in Pandas?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn