How to Delete Rows from a Pandas DataFrame Based on a Conditional Expression?

DDD
Release: 2024-11-13 15:23:02
Original
602 people have browsed it

How to Delete Rows from a Pandas DataFrame Based on a Conditional Expression?

Removing Rows from Pandas DataFrame Based on Conditional Expression

Your approach of using df[(len(df['column name']) < 2)] to delete rows where the string length exceeds 2 is incorrect. This results in a KeyError because the expression evaluates to a boolean DataFrame with keys True and False, rather than row indices.

To delete rows based on a conditional expression, you can utilize the drop method. Here's how it works:

Using drop() to Delete Rows

df = df.drop(df[df['column name'].str.len() > 2].index)</p>
<p>In this example, df['column name'].str.len() > 2 creates a boolean DataFrame indicating rows with string lengths greater than 2. The index attribute of this DataFrame retrieves the indices of those rows, which are then passed to drop().</p>
<p><strong>Alternative Syntax</strong></p>
<pre class="brush:php;toolbar:false">df = df.drop(df[(df['column name'].str.len() > 2)].index)
Copy after login

This syntax provides a clearer separation between the boolean DataFrame and index extraction.

Multiple Conditions

Boolean indexing allows you to combine conditions using logical operators. For instance, to remove rows where the string length exceeds 2 and the score is less than 50:

df = df.drop(df[(df['column name'].str.len() > 2) & (df['score'] < 50)].index)
Copy after login

The above is the detailed content of How to Delete Rows from a Pandas DataFrame Based on a Conditional Expression?. 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