How to get a single value as a string from pandas data frame


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']

enter image description here


Asked By: Oamar Kanji



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

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

Or, similarly,

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

…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['Host'].eq('a').idxmax(), 'Port']

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

Answered By: cs95

it should work simply..

>>> df
  Host Port
0    a    b
>>> df[df['Host'] == 'a']['Port'][0]   # will choose the first index simply which is 'b'

OR, use with print which will strip off the surrounded single ticks.

>>> print(df[df['Host'] == 'a']['Port'][0])

This will easier because you have just choose the desired Index even if you have Multiple values across Port columns


>>> df
  Host Port
0    a    b
1    c    c

Looking for distinct a & c based on Index:

>>> df[df['Host'] == 'a']['Port'][0]
>>> df[df['Host'] == 'c']['Port'][1]
Answered By: Karn Kumar

As mentioned in my comment, using [1] should work afterwards, to pull the variable you’re looking for.

t = df[df['Host'] == 'a']['Port'][1]
Answered By: PL200
t = df['Host'].values[0] 

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

t = str(df['Host'].values[0])
Answered By: Javi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.