1

I would like to filter based on a string condition.

My dataframe looks like this:

dataframe

I want to group by Id, and filter for groups that consist of both words: "add" and "set". Additional elements like close do not matter. I only want to filter groups with "set" and "add.

My final output should look like this:

final output

I've tried this:

df = df.groupby(['id']).filter(lambda x: (x.mode == "set" & x.mode == "add").all())

But this wil give me an error message: unsupported operand type(s) for &: 'str' and 'method'

Let me know of other solutions. Thanks!

2

1 Answer 1

5

The error you get is because .mode is a method on the DataFrame. Use ["mode"] instead.

To filter the groups correctly you want to test whether "set" is appears in the list of modes and "add" appears in the list of modes. The code should look like this:

df.groupby("id").filter(lambda x: (x["mode"] == "set").any() & (x["mode"] == "add").any())                                                                                                                                                   
Sign up to request clarification or add additional context in comments.

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.