Reputation: 861
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.
Upvotes: 11
Views: 25546
Reputation: 88
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.
Upvotes: 1
Reputation: 210832
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']]
Upvotes: 29