0

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!

R_abcdefg
  • 145
  • 1
  • 11
  • You should probably start off reading a simple tutorial like https://pandas.pydata.org/pandas-docs/stable/10min.html . I don't think you understand what `groupby` does – Josh Friedlander Apr 04 '19 at 09:42
  • 1
    Please take a look at [How to make a good reproducible pandas example](https://stackoverflow.com/a/20159305/463796). The data should be included as a formatted code, not as a screenshot. – w-m Apr 04 '19 at 09:49

1 Answers1

4

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())                                                                                                                                                   
w-m
  • 10,772
  • 1
  • 42
  • 49