Flemming Juel Jensen
Flemming Juel Jensen

Reputation: 17

Iterate over all rows in dataframe and check all column values are in list

I have a dataframe with 7 columns and ~5.000 rows. I want to check that all the column values in a row are in my list and if so either add them to a new dataframe OR remove those where all values do not match, i.e. remove false rows (w/e is the easiest);

for row in df:
   for columns in row:
      if df.iloc[row, column].isin(MyList):
         ...*something*

I could imagine that .apply and .all could be used, but I'm afraid my python skills are limited, any help?

Upvotes: 0

Views: 1191

Answers (1)

jfaccioni
jfaccioni

Reputation: 7519

If I understood correctly, you can solve this by using apply with a lambda expression like:

df.loc[df.apply(lambda row: all(value in MyList for value in row), axis=1))]

Upvotes: 1

Related Questions