3

I am trying to query a pandas dataframe for rows in which one column contains a tuple containing a certain value.

As an example:

   User                 Col1
0     1     (cat, dog, goat)
1     1         (cat, sheep)
2     1        (sheep, goat)
3     2          (cat, lion)
4     2  (fish, goat, lemur)
5     3           (cat, dog)
6     4          (dog, goat)
7     4                  cat

So assuming I want to return the rows where Col1 contains 'cat', is there a way to do this without iterating through each row and performing an "if" (my actual dataset has many more rows)?

df['Col1'].isin(['cat'])

and

df['Col1'].str.contains("cat")

only return 'true' for the last row

3 Answers 3

3

You could use a lambda function within apply():

df[df["Col1"].apply(lambda x: "cat" in x)]

The lambda returns True when "cat" is in the cell. That works for both strings ("cat" in "cat" is True) and tuples ("cat" in ("cat", "dog") is True). By subsetting the df, you get all rows where the lambda is True.

Sign up to request clarification or add additional context in comments.

3 Comments

Glad I could help!
You could also just write df[df["Col1"].apply(lambda x: "cat" in x)]
You're right, @NoelEvans! Changed accordingly.
1

Why not subset your data frame and then output its results?

catdf = df[df['Col1'].str.contains("cat")]

Comments

1

Your DataFrame column contains a mixture of strings and tuples. I don't think you can avoid iterating the column. But you can iterate efficiently with the apply method. Example code follows.

import pandas as pd

# fake data - in a Series for simplicity
tlist = [('cat', 'dog', 'goat'),
    ('cat', 'sheep'),
    ('sheep', 'goat'),
    ('cat', 'lion'),
    ('fish', 'goat', 'lemur'),
    ('cat', 'dog'),
    ('dog', 'goat'),
    'cat']
s = pd.Series(tlist)

# iterate Series with a lambda function searching for 'cat'
s.apply(lambda x: 'cat' in x)

Which gave me the following output

Out[38]: 
0     True
1     True
2    False
3     True
4    False
5     True
6    False
7     True
dtype: bool

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.