close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to get a single value as a string from pandas data frame in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

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

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

  2. get a single value as a string from pandas data frame

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

Method 1

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).

Method 2

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

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

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

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

Example:

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

Looking for distinct a & c based on Index:

>>> df[df['Host'] == 'a']['Port'][0]
'b'
>>> df[df['Host'] == 'c']['Port'][1]
'c'

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read