filter pandas dataframe by several column values

Question:

I would like to filter a df by several columns, is it possible to do it in one line?

so far I did it over many lines:

mini_df = df[df[‘col1’]==0]
mini_df = mini_df[mini_df[‘col2’]==1]

but if I do mini_df = df[df['col1']==0 and df['col2']==1] it does not work. since I want to have many such filters would be good to be able to do them in one line.

Asked By: alberto

||

Answers:

you were close, try to put every filter in brackets () and "&" instead of "and":

mini_df = df[(df['col1']==0) & (df['col2']==1)]
Answered By: ArieAI
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.