Miguel Lebon
Miguel Lebon

Reputation: 49

Filter pandas dataframe in python3 depending on the value of a list

So I have a dataframe like this:

df = {'c': ['A','B','C','D'],
      'x': [[1,2,3],[2],[1,3],[1,2,5]]}

And I want to create another dataframe that contains only the rows that have a certain value contained in the lists of x. For example, if I only want the ones that contain a 3, to get something like:

df2 = {'c': ['A','C'],
       'x': [[1,2,3],[1,3]]}

I am trying to do something like this:

df2 = df[(3 in df.x.tolist())]

But I am getting a

KeyError: False

exception. Any suggestion/idea? Many thanks!!!

Upvotes: 0

Views: 28

Answers (2)

Subbu VidyaSekar
Subbu VidyaSekar

Reputation: 2615

Below code would help you

To create the Correct dataframe

df = pd.DataFrame({'c': ['A','B','C','D'],
      'x': [[1,2,3],[2],[1,3],[1,2,5]]})

To filter the rows which contains 3

df[df.x.apply(lambda x: 3 in x)==True]

Output:

   c    x
0  A   [1, 2, 3]
2  C   [1, 3]

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195543

df = df[df.x.apply(lambda x: 3 in x)]
print(df)

Prints:

   c          x
0  A  [1, 2, 3]
2  C     [1, 3]

Upvotes: 2

Related Questions