Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a cell value from a Dataframe in Pandas

I have a dataframe with 3 columns, like this:

enter image description here

I want to search for 12295682 in instrument_token column and extract the related tradingsymbol UBL20JANFUT.

How do I do that?

thanks in advance

like image 873
KawaiKx Avatar asked Dec 22 '19 05:12

KawaiKx


People also ask

How do I extract values from a DataFrame 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.


3 Answers

You can use boolean indexing with DataFrame.loc for filter by condition and by column name:

s = df.loc[df['instrument_token'].eq(12295682), 'tradingsymbol']
#alternative
s = df.loc[df['instrument_token'] == 12295682, 'tradingsymbol']

And then get first value of Series:

a = s.iat[0]
a = s.iloc[0]
a = s.tolist()[0]
a = s.to_array()[0]
#general solution if not match condition and select first value failed
a = next(iter(s), 'no match')

Another idea is use DataFrame.set_index fo index by column instrument_token:

df = df.set_index('instrument_token')

Anf then select by DataFrame.loc or DataFrame.at:

a = df.loc[12295682, 'tradingsymbol']
a = df.at[12295682, 'tradingsymbol']
like image 154
jezrael Avatar answered Sep 19 '22 05:09

jezrael


You can use:

list(df.loc[df['instrument_token'] == '12295682', 'tradingsymbol'])[0]

# UBL20JANFUT
like image 42
oppressionslayer Avatar answered Sep 18 '22 05:09

oppressionslayer


try

df[df['instrument_token'] == 12295682]['tradingsymbol']
like image 41
Kenan Avatar answered Sep 22 '22 05:09

Kenan