I have two columns in a dataframe namely 'origin' and 'destination' which contains the names of different places. I need to remove the rows that don't contain 'PHX', 'JFK', 'NTU' in either of these columns. If atleast one among the 2 columns has one of these 3 places, the row can stay, else the row must be dropped altogether. Can you please help me to code this part ?
This snippet should do the work:
city = ['PHX', 'JFK', 'NTU'] colomn_to_exclude = df.apply(lambda row: (row['origin'] not in city) and (row['destination'] not in city)) new_df = df[~colomn_to_exclude]
the second line checks the lines where your exclusion condition is verified and the line after subset the dataframe accordingly.
You could also write something like
colomn_to_exclude = df.apply(lambda row: (row['origin'] not in city) and (row['destination'] not in city)) df.drop(~colomn_to_exclude, axis=1, inplace=True)
and you won't have to make a copy of your dataframe