Home >Backend Development >Python Tutorial >How to Select Rows in a DataFrame Between Two Values?

How to Select Rows in a DataFrame Between Two Values?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-16 00:28:03730browse

How to Select Rows in a DataFrame Between Two Values?

Selecting Rows in a DataFrame Between Two Values

When working with DataFrames, you may need to filter the data based on specific criteria. One common scenario is selecting rows where the values in a particular column fall within a specified range.

Problem:

You have a DataFrame df and want to modify it to include only rows for which the values in the column closing_price are between 99 and 101. You try the following code:

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

However, you encounter the error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

Solution:

To resolve this issue, use the between method of the Series:

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

The between method takes two arguments: the lower and upper bounds of the range. It returns a boolean Series indicating which rows meet the specified condition. By passing this boolean Series to the square brackets ([]), you can select the corresponding rows from the DataFrame.

The above is the detailed content of How to Select Rows in a DataFrame Between Two Values?. 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