18

i have a table in my pandas dataframe. df

id count price
1    2     100
2    7      25
3    3     720
4    7     221
5    8     212
6    2     200

i want to create a new dataframe(df2) from this, selecting rows where count is 2 and price is 100,and count is 7 and price is 221

my output should be df2 =

id count price
1    2     100
4    7     221

i am trying using df[df['count'] == '2' & df['price'] == '100']

but getting error

TypeError: cannot compare a dtyped [object] array with a scalar of type [bool]
1
  • It's a classic: df[(df['count'] == '2') & (df['price'] == '100')]. Commented Nov 30, 2016 at 10:03

1 Answer 1

21

You need to add () because & has higher precedence than ==:

df3 = df[(df['count'] == '2') & (df['price'] == '100')]
print (df3)
  id count price
0  1     2   100

If you need to check multiple values use isin:

df4 = df[(df['count'].isin(['2','7'])) & (df['price'].isin(['100', '221']))]
print (df4)
  id count price
0  1     2   100
3  4     7   221

But if you need to check numeric value of row elements, use:

df3 = df[(df['count'] == 2) & (df['price'] == 100)]
print (df3)

df4 = df[(df['count'].isin([2,7])) & (df['price'].isin([100, 221]))]
print (df4)
Sign up to request clarification or add additional context in comments.

2 Comments

but how do i join two results in 1 df.? i was thinking of creating two different dataframe for my two rows that i want and then append them? is there any other way to do it?
Do you think assign to df3 or df4 ?

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.