首页  >  文章  >  后端开发  >  如何根据条件表达式删除 Pandas DataFrame 中的行?

如何根据条件表达式删除 Pandas DataFrame 中的行?

DDD
DDD原创
2024-11-14 18:34:02916浏览

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)

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)

以上是如何根据条件表达式删除 Pandas DataFrame 中的行?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn