The easiest way to return only the location value from a data frame

This is a very simple question, but I always found that I was performing too many operations to get one location value from the data framework. let me explain:

import pandas as pd
df = pd.DataFrame(list(zip('abcde', 'rithf')), columns=['a', 'b'])
df
Out[23]: 
   a  b
0  a  r
1  b  i
2  c  t
3  d  h
4  e  f

I am trying to extract the value of column b, where column a == a. using .loc, which is very direct, will return this:

df.loc[df.a == 'a', 'b']
Out[24]: 
0    r
Name: b, dtype: object

getting the value becomes very dirty:

df.loc[df.a == 'a', 'b'].values[0]
Out[26]: 
'r'

when you know the exact index, it actually only returns the value:

df.loc[0, 'b']
Out[27]: 
'r'

but obviously i need an index first.

so the question is is there a sexier way df.loc[df.a == 'a', 'b'].values[0]to return only the actual value, not aseries

+4
source share
2 answers

Series.item:

print(df.loc[df.a == 'a', 'b'].item())
r
+2

argmax , .loc -

df.loc[(df.a=='a').argmax(),'b']

, , 'a'.

-

In [346]: df
Out[346]: 
   a  b
0  a  r
1  b  i
2  c  t
3  d  h
4  e  f

In [347]: (df.a=='a').argmax() # row indexer
Out[347]: 0

In [348]: df.loc[(df.a=='a').argmax(),'b']
Out[348]: 'r'
+1

Source: https://habr.com/ru/post/1682413/


All Articles