Returning A String From .loc Query

Viewed 3523

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.

4 Answers

@anky_91 is right. You should use .iloc, for this case.

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

Try this -

df.loc[df[df['Age'] == 15].index[0], 'Name']

I recommend to consider the use of query. If you only want to get the str, you can use:

df.query('Age==15').Name.values[0]

This might be more intuitive given the first try of Ron.

Related