Python Pandas – select dataframe columns where equals

Question:

What is the Pandas equivalent of this SQL code?

Select id, fname, lname from table where id = 123

I know that this is the equivalent of an SQL ‘where’ clause in Pandas:

df[df['id']==123]

And this selects specific columns:

df[['id','fname','lname']]

But I can’t figure out how to combine them. All examples I’ve seen online select all columns with conditions. I want to select a limited number of columns with one or more conditions.

Asked By: Dread

||

Answers:

Use SQL-like .query() method:

df.query("id == 123")[['id','fname','lname']]

or

df[['id','fname','lname']].query("id == 123")

or more “Pandaic”:

df.loc[df['id'] == 123, ['id','fname','lname']]

Extending on @MaxU’s answer, suppose you needed multiple column values, taking ‘fname’

df[['id','fname','lname']].query("fname == ('simon', 'michael')")

Without using query method of @MaxU, for simplicity included all columns:

df[df.fname.isin(['simon', 'michael'])]

Cascading the above with [[‘id’,’fname’,’lname’]] will give the needed answer.

Answered By: silicon23
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.