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.
以上がPandas で値の範囲に基づいて DataFrame 行をフィルターするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。