Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude rows from dataframe except if another column condition met

I would like to exclude rows from my dataframe if they meet a list (eligibility_criteria) condition, unless the tariff column starts with '***'. This is what I have:

import pandas as pd

df = df[~df['eligibility'].str.contains(eligibility_criteria, na=False)] #This works

How do I add this 'except when' qualifier...

#df['tariff'].str.startswith("***")
like image 374
Deskjokey Avatar asked Jan 20 '26 03:01

Deskjokey


1 Answers

Let E be the eligibility criterion and S be true if the tariff starts with "***". You want to exclude the rows that are E unless S which is the same as E & ~S. Conversely, you want to keep the rows that do not have this property: ~(E & ~S), which is the same as ~E | S:

df = df[~df['eligibility'].str.contains(eligibility_criteria, na=False) | 
         df['tariff'].str.startswith("***")]
like image 157
DYZ Avatar answered Jan 22 '26 15:01

DYZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!