简体   繁体   中英

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.

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 ; However I wish to retain the rows that contain 0. I am still researching, any suggestion is appreciated

Use df.drop() to remove rows from DataFrame.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM