Home > Backend Development > Python Tutorial > How to Delete Rows in a Pandas DataFrame Based on a Conditional Expression?

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

DDD
Release: 2024-11-14 18:34:02
Original
982 people have browsed it

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

Conditional Row Deletion in Pandas DataFrames

To address the issue raised in the question about deleting rows based on a conditional expression in a pandas DataFrame, we can employ the drop method. This method allows us to remove rows from a DataFrame based on specific criteria.

For instance, to delete rows where the string length in a particular column exceeds 2, we can use the following code:

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

The str.len() function returns the length of each string in the specified column, and we apply the condition to each element in the DataFrame using the > operator. Rows where the condition is met are then deleted.

Additionally, if we want to delete multiple rows based on multiple conditions, we can use the bitwise operators (| for OR, & for AND, and ~ for NOT) within parentheses to group our conditions.

For example, to delete rows where the values in column 'score' are 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 Delete Rows in 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