1

I want to use loc to filter on multiple cities for the column Name

I've tried filtering using several column names:

popdemo_df.loc[popdemo_df['Name'] == 'Richmond city', ['Name'] == Landsdowne']

I get the following error:

False, unexpected EOF while parsing

rje
  • 6,388
  • 1
  • 21
  • 40
ramango
  • 21
  • 1
  • 5
  • `popdemo_df.loc[(popdemo_df['Name'] == 'Richmond city') | (popdemo_df['Name'] == 'Landsdowne')]` – Brian Sep 09 '19 at 17:46

3 Answers3

3

In order to combine Boolean indices, you need to surround them with parentheses and use the bitwise operators &, |, or ~, like so:

# Selects rows where either condition is met
popdemo_df.loc[(popdemo_df['Name'] == 'Richmond city') | (popdemo_df['Name'] == 'Landsdowne')]

You can do the same with Series.isin() as well:

popdemo_df.loc[popdemo_df['Name'].isin(['Richmond city', 'Landsdowne'])]
PaSTE
  • 4,050
  • 18
  • 26
0

Use isin:

popdemo_df.loc[popdemo_df['Name'].isin(['Richmond city','Landsdowne'])]
rje
  • 6,388
  • 1
  • 21
  • 40
  • While this is the way to do this, I just want to point out to OP that your problem wasn't not using `isin`, your problem was using a comma between dataframe masks and not an pipe (|). As well as calling `['Name']` without a dataframe. – Brian Sep 09 '19 at 17:48
  • you mean |? it would be impossible for ['Name'] to be two unique values at once – Derek Eden Sep 09 '19 at 17:51
0

Commas are used to separate rows and columns inside df.loc brackets. To combine conditionals, you can use & for and, | for or and ~ for not.

Try this instead:

popdemo_df.loc[:, popdemo_df['Name'] == 'Richmond city' | popdemo_df['Name'] == 'Landsdowne']
jfaccioni
  • 7,099
  • 1
  • 9
  • 25