user16454053
user16454053

Reputation: 109

Selecting elements of one column based on values from another column

I have data in this shape.

a    b c d e f
1    2 3 4 5 1m
7    8 9 1 2 1m
3.08 4 5 6 7 2   
8    2 8 3 2 2
4    5 3 7 9 2

I am trying to selects elements of column 'a' which have values 2 in column 'f'.

I was trying to use this:

elements = df.query('f==2')['a']

After trying to print elements I am getting this:

Series([], Name: a, dtype: float64)

I think problem is coming from the two elements 1m in column 'f' but do not understand why and how can overcome this? Can someone help me to understand what is going on?

Upvotes: 0

Views: 1839

Answers (1)

Rodalm
Rodalm

Reputation: 5513

It seems that the numerical values of the f column are strings. query is interpreting them as integers.

This should work

elements = df.query('f == "2"')['a']

But I think using loc is better here

elements = df.loc[df.f == '2', 'a']

Upvotes: 4

Related Questions