Carlo
Carlo

Reputation: 441

Multiple filters Python Data.frame

I'm pretty new to python. I'm trying to filter rows in a data.frame as I do in R.

sub_df = df[df[main_id]==3]

works, but

df[df[main_id] in [3,7]]

gives me error

"The truth value of a Series is ambiguous"

Can you please suggest me a correct syntax to write similar selections?

Upvotes: 3

Views: 102

Answers (3)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210922

yet another solution:

In [60]: df = pd.DataFrame({'main_id': [0,1, 2, 3], 'x': list('ABCD')})

In [61]: df
Out[61]:
   main_id  x
0        0  A
1        1  B
2        2  C
3        3  D

In [62]: df.query("main_id in [0,3]")
Out[62]:
   main_id  x
0        0  A
3        3  D

Upvotes: 0

jotasi
jotasi

Reputation: 5177

You can use pandas isin function. This would look like this:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'f']})
df[df['A'].isin([2, 3])]

giving:

   A  B
1  2  b
2  3  f

Upvotes: 2

languitar
languitar

Reputation: 6784

df[df[main_id].apply(lambda x: x in [3, 7])]

Upvotes: 1

Related Questions