Explore Courses Blog Tutorials Interview Questions
0 votes
in Data Science by (17.6k points)

I am kind of getting stuck on extracting value of one variable conditioning on another variable. For example, the following dataframe:

A  B

p1 1

p1 2

p3 3

p2 4

How can I get the value of A when B=3? Every time when I extracted the value of A, I got an object, not a string.

1 Answer

0 votes
by (41.4k points)

To get the series that satisfy our condition use loc and then to get the first element use iloc:

In [2]: df


    A  B

0  p1  1

1  p1  2

2  p3  3

3  p2  4

In [3]: df.loc[df['B'] == 3, 'A']


2    p3

Name: A, dtype: object

In [4]: df.loc[df['B'] == 3, 'A'].iloc[0]

Out[4]: 'p3'

If you wish to learn more about Data Science, visit Data Science tutorial and Data Science courses by Intellipaat.

Browse Categories