Home > Mobile >  Converting an element of a dataframe into string element - python
Converting an element of a dataframe into string element - python

Time:10-22

In python, I have such a data frame:

pn

Out[249]: 
   a  b   c    d    e
2  4  8  12  131  127


cn.dtypes
Out[253]: 
c1    object
c2    object
c3    object
dtype: object

I want to select pn["b"] as string.

When I paste below, I get the below value:

pn["b"]
Out[257]: 
2    8
Name: b, dtype: object

But I want the output to be as string:

Like below x:

x="8"

x
Out[259]: '8'

How can I do that?

I will be very glad for any help.

Thanks for any help.

CodePudding user response:

You can cast the column b to string type using astype method and then use iloc to access the specific row.

>>> import pandas as pd
>>>
>>> pn = pd.DataFrame({'b': [8]}, index=[2])
>>> pn
   b
2  8
>>> pn['b'].astype(str).iloc[0]
'8'
>>> type(pn['b'].astype(str).iloc[0])
<class 'str'>
  • Related