Jane Wayne
Jane Wayne

Reputation: 8855

How do I filter for rows in a Pandas dataframe based on a column that has list as values?

I have a Pandas dataframe where one of the columns stores lists of string literals. For example, my data looks like the following.

field1, field2
x1, ['tag1', 'tag2']
x2, ['tag1', 'tag3']

I want to get only the records in this dataframe whose field2 list contains tag1 or tag2. So, in the example above, only the record where field1=x1 should be returned.

How can I do this filtering on a Pandas dataframe?

Upvotes: 0

Views: 47

Answers (1)

harpan
harpan

Reputation: 8631

You need to check for tag2 in the list of field2. Using .apply(), you can achieve this.

df[df.apply(lambda x: 'tag2' in x['field2'],axis=1)]

Output:

    field1  field2
0   x1      [tag1, tag2]

Upvotes: 1

Related Questions