Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract column value based on another column pandas dataframe

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.

like image 530
Gejun Avatar asked Apr 18 '16 01:04

Gejun


People also ask

How do I get a column value of a pandas DataFrame based on another column?

You can extract a column of pandas DataFrame based on another value by using the DataFrame. query() method. The query() is used to query the columns of a DataFrame with a boolean expression.

How do you see if values in one column are in another pandas?

You can check if a column contains/exists a particular value (string/int), list of multiple values in pandas DataFrame by using pd. series() , in operator, pandas. series.

How do I create a conditional column in pandas?

You can create a conditional column in pandas DataFrame by using np. where() , np. select() , DataFrame. map() , DataFrame.


1 Answers

You could use loc to get series which satisfying your condition and then iloc to get first element:

In [2]: df Out[2]:     A  B 0  p1  1 1  p1  2 2  p3  3 3  p2  4  In [3]: df.loc[df['B'] == 3, 'A'] Out[3]: 2    p3 Name: A, dtype: object  In [4]: df.loc[df['B'] == 3, 'A'].iloc[0] Out[4]: 'p3' 
like image 178
Anton Protopopov Avatar answered Oct 05 '22 23:10

Anton Protopopov