简体   繁体   English

仅当使用 Pandas 满足特定条件时,才删除 dataframe 中的行

[英]Remove rows in dataframe only if a certain condition is met using Pandas

I have a dataframe where I would like to remove the rows from the ['Date'] column that contains.22 and.23 only if the energy column contains a value > 0.我有一个 dataframe ,我想从包含 22 和 23 的 ['Date'] 列中删除行,前提是能量列包含的值 > 0。

Data数据

ID  Date    type    energy
AA  Q1.22   ok      8
AA  Q2.22   n       9
AA  Q3.22   yes     8
AA  Q1.23   ok      5
BB  Q1.22   no      8
BB  Q2.22   ok      8
BB  Q3.22           0
BB  Q1.23           0               

Desired期望的

ID  Date    type    energy
BB  Q3.22           0
BB  Q1.23           0               

Doing正在做

df1 = df.drop(df[df.energy > 0].index) & df[df.Date.str.contains(".22|.23") == False]

However this is actually removing the rows that contain 0 ;然而,这实际上是删除包含 0 的行 However I wish to retain the rows that contain 0. I am still researching, any suggestion is appreciated但是我希望保留包含 0 的行。我仍在研究中,欢迎提出任何建议

Use df.drop() to remove rows from DataFrame.使用 df.drop() 从 DataFrame 中删除行。

df.drop(df[(df["Date"].str.contains(pat=".22 |.23") == False) & (df["energy"] > 0)].index) df.drop(df[(df["Date"].str.contains(pat=".22 |.23") == False) & (df["energy"] > 0)].index)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 熊猫:如果满足条件删除行 - pandas: remove rows if condition is met 如何根据特定条件删除 Pandas DataFrame 的行? - How do I remove rows of a Pandas DataFrame based on a certain condition? Pandas 适用,但仅适用于满足条件的行 - Pandas apply but only for rows where a condition is met 如何在Python Pandas数据帧列上执行数学运算,但仅限于满足某个条件? - How do I perform a math operation on a Python Pandas dataframe column, but only if a certain condition is met? 如何向仅在满足特定条件时增加的 pyspark 数据帧行添加 ID? - How to add an ID to pyspark dataframe rows that increases only if a certain condition is met? 每次在 pandas dataframe 中满足某个条件时如何增加一个值 - how to increment a value every time a certain condition is met in pandas dataframe Pandas:标记重叠日期但如果满足条件则排除某些行 - Pandas: Flag overlapping dates but exclude certain rows if condition is met Pandas DataFrame 在满足条件的前一行中查找最近的索引 - Pandas DataFrame find closest index in previous rows where condition is met 如果满足条件,如何删除 pandas dataframe 中的特定行 - How to delete specific rows in pandas dataframe if a condition is met Pandas dataframe 行在满足一个条件时错误地丢弃 - Pandas dataframe rows incorrectly dropping when one condition is met
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM