1

Let's say we have this df

d = pd.DataFrame({'year': [2010, 2020, 2010], 'colors': ['red', 'white', 'blue'], "shirt" : ["red shirt", "green and red shirt", "yellow shirt"] })

like this:

    year    colors  shirt
0   2010    red     red shirt
1   2020    white   green and red shirt
2   2010    blue    yellow shirt

I want to filter out rows in which the "shirt" column contains the "colors" column also considering the "year" column

desired output:

year    colors  shirt
    0   2010    red     red shirt

I tried this d[(d.year == 2010) & (d.shirt.str.contains(d.colors))] but I am getting this error:

'Series' objects are mutable, thus they cannot be hashed

It is a big df that I am working on. How can I solve with some pandas function?

3
  • do a join by pipe on the string contains: d[(d.year == 2010) & (d.shirt.str.contains('|'.join(d.colors)))]..? Commented Sep 24, 2020 at 17:16
  • @anky what was the reason for the error? Commented Sep 24, 2020 at 18:02
  • 1
    Actually looking at your example the answer by Rakesh should be more apt, as str contains with a pattern for all rows will even match something not in the current row Commented Sep 24, 2020 at 18:07

1 Answer 1

2

I believe you need df.apply

Ex:

df = pd.DataFrame({'year': [2010, 2020, 2010], 'colors': ['red', 'white', 'blue'], "shirt" : ["red shirt", "green and red shirt", "yellow shirt"] })
print(df[(df.year == 2010) & df.apply(lambda x: x.colors in x.shirt, axis=1)])

Output:

   year colors      shirt
0  2010    red  red shirt
Sign up to request clarification or add additional context in comments.

3 Comments

I thought about it, I was hoping for some pandas function but this works too!
@anky sorry i am not able to think on how to use a list comprehension here.
No Problem , i meant something like: d[d['year'].eq(2010) & [a in b for a,b in zip(d['colors'],d['shirt'])]]

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.