Question

How to get a single value as a string from pandas dataframe

I am querying a single value from my data frame which seems to be 'dtype: object'. I simply want to print the value as it is with out printing the index or other information as well. How do I do this?

col_names = ['Host', 'Port']
df = pd.DataFrame(columns=col_names)
df.loc[len(df)] = ['a', 'b']

t = df[df['Host'] == 'a']['Port']
print(t)

OUTPUT: enter image description here

EXPECTED OUTPUT: b

 46  109078  46
1 Jan 1970

Solution

 73

If you can guarantee only one result is returned, use loc and call item:

>>> df.loc[df['Host'] == 'a', 'Port'].item()
'b'

Or, similarly,

>>> df.loc[df['Host'] == 'a', 'Port'].values[0]
'b'

...to get the first value (similarly, .values[1] for the second). Which is better than df.loc[df['Host'] == 'a', 'Port'][0] because, if your DataFrame looks like this,

  Host Port
1    a    b

Then "KeyError: 0" will be thrown—

df.loc[df['Host'] == 'a', 'Port'][0]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)

Alternatively, use at:

>>> df.at[df['Host'].eq('a').idxmax(), 'Port']
'b'

The drawback is that if 'a' doesn't exist, idxmax will return the first index (and return an incorrect result).

2018-11-12

Solution

 9
t = df['Host'].values[0] 

will give you the first value. If you need a string, just do:

t = str(df['Host'].values[0])
2022-06-27