Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning A String From .loc Query

I have a simple pandas dataframe:

import pandas as pd 
data = [['tom', 10], ['nick', 15], ['juli', 14]] 
df = pd.DataFrame(data, columns = ['Name', 'Age'])

If I select the Name from row index 1, I get a simple string object:

df.loc[1].Name
Out[9]: 'nick'

But if I select the row containing Age == 15, I get an object I can't seem to coerce into a string object

df.loc[df.Age==15].Name
Out[11]:1    nick
Name: Name, dtype: object
type(df.loc[df.Age==15].Name)
Out[38]: pandas.core.series.Series

Ok, its a series, that's cool, get the first element:

df.loc[df.Age==15].Name[0]
KeyError: 0

Well, that didn't work, lets ask for the actual key:

df.loc[df.Age==15].Name[1]
Out[40]: 'nick'

Yeah! That works! ... but if I knew the actual key I wouldn't have done the query in the first place!

How do I get the string value from this Name field if I know the Age? In my real use-case I know Age is unique.

like image 537
Ron Jensen Avatar asked Jun 17 '26 16:06

Ron Jensen


1 Answers

As @ayhan said in comment above, you can use pandas.Series.item() like this:

>>> df.loc[df.Age==15, 'Name'].values.item()
'nick'

You can also use pandas.Series.array:

>>> df.loc[df.Age==15, 'Name'].array[0]
'nick'

or pandas.Series.to_numpy:

>>> df.loc[df.Age==15, 'Name'].to_numpy()[0]
'nick'
like image 187
Jaroslav Bezděk Avatar answered Jun 20 '26 06:06

Jaroslav Bezděk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!