How to Remove Rows from a Pandas DataFrame Based on a Condition?

DDD
Release: 2024-11-12 08:50:02
Original
167 people have browsed it

How to Remove Rows from a Pandas DataFrame Based on a Condition?

Conditional Deletion of Rows in Pandas DataFrames

The original question sought to remove rows from a DataFrame based on the string length of a specific column. While the proposed solution was incorrect, this article aims to provide a comprehensive understanding of conditional row deletion in Pandas.

Using the drop Method

To directly address the title's question, the drop method offers a straightforward approach for eliminating rows based on a conditional expression. The syntax is as follows:

df = df.drop(some labels)
df = df.drop(df[<some boolean condition>].index)
Copy after login

Example

To remove all rows where the score column value is less than 50:

df = df.drop(df[df.score < 50].index)
Copy after login

For an in-place modification, you can use:

df.drop(df[df.score < 50].index, inplace=True)
Copy after login

Multiple Conditions

Pandas supports the use of logical operators (| for OR, & for AND, ~ for NOT) for creating complex conditions. Remember to enclose them in parentheses.

To remove all rows where score is both less than 50 and greater than 20:

df = df.drop(df[(df.score < 50) & (df.score > 20)].index)
Copy after login

The above is the detailed content of How to Remove Rows from a Pandas DataFrame Based on a Condition?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template