2

Can't get my head around the Pandas syntax for this. Here's some example data:

one  two   three  id
12   34    561    13555
2    67    781    14777 
34   12    90     13555    
5    67    89     14777

I want to return columns one, two and id where the value in the id column is 13555. Want to select the columns by name, not position.

Output would look like this:

one  two  id
12   34   13555
34   12   13555    

2 Answers 2

4

You can try loc and isin:

print df.loc[(df.id.isin([13555])), ['one', 'two', 'id']]

   one  two     id
0   12   34  13555
2   34   12  13555

Or:

df = df[['one', 'two', 'id']]
print df
   one  two     id
0   12   34  13555
1    2   67  14777
2   34   12  13555
3    5   67  14777

print df[df.id == 13555]
   one  two     id
0   12   34  13555
2   34   12  13555

print df[['one', 'two', 'id']][df.id == 13555]
   one  two     id
0   12   34  13555
2   34   12  13555

Or use query:

print df[['one', 'two', 'id']].query("id == 13555")
   one  two     id
0   12   34  13555
2   34   12  13555
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming your dataframe is named df_name, you can:

line_selector = df_name.id == 13555
df_name.loc[line_selector, ['one', 'two', 'id']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.