Python Pandas - select dataframe columns where equals

What is the Pandas equivalent of this SQL code?

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

I know this is the equivalent of the SQL 'where' clause in Pandas:

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

And this selects specific columns:

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

But I can’t understand how to combine them. All the examples that I saw on the Internet select all columns with conditions. I want to select a limited number of columns with one or more conditions.

+4
source share
1 answer

Use an SQL-like method .query():

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']]
+5
source

Source: https://habr.com/ru/post/1684771/


All Articles