0

Given the following example.

d = {'col1': [1, 2, 3], 'col2': [6, 7]}

df = pd.DataFrame(data=d)

df
   col1  col2
0     1     6
1     2     7

newdf[df['col1' ==2]

newdf

   col1  col2
0     2     7

Works just fine for single col

but

newdf[df['col1' ==2 & 'col2' == 7]

I win error prize.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Rayl54292
  • 95
  • 2
  • 8
  • 1
    Does this answer your question? [Efficient way to apply multiple filters to pandas DataFrame or Series](https://stackoverflow.com/questions/13611065/efficient-way-to-apply-multiple-filters-to-pandas-dataframe-or-series) – sjw Jun 18 '20 at 16:34
  • Specifically, see the third example in the accepted answer in the linked question. – sjw Jun 18 '20 at 16:35

2 Answers2

0
  • None of the following are correct

    • newdf[df['col1' ==2]
    • newdf[df['col1' ==2 & 'col2' == 7]
    • newdf[df['col1' == 2 && 'col2' == 7]
  • Parenthesis must be around each condition

  • Pandas: Boolean indexing
import pandas as pd

d = {'col1': [1, 2, 3, 2], 'col2': [6, 7, 8, 9]}
df = pd.DataFrame(data=d)

   col1  col2
0     1     6
1     2     7
2     3     8
3     2     9

# specify multiple conditions
newdf = df[(df.col1 == 2) & (df.col2 == 7)]
print(newdf)

   col1  col2
1     2     7
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
0

You have a typo in your statement. The logical and operator in python is

and

Your statement should be

>>> newdf[df[('col1' == 2) & ('col2' == 7)]

Thanks @Trenton for the remark.

Dorian
  • 1,439
  • 1
  • 11
  • 26