Dance Party2
Dance Party2

Reputation: 7536

Pandas Object to String

So I have this data frame...

import pandas as pd
df = pd.DataFrame({'COL1':['A','A','B','B']})

I want to extract the first 'A' from COL1 as a string value so it looks like this: 'A' in Python because when I use it in a chart title via MatPlotLib, it displays as '0 A dtype:object' instead of just 'A.'

Thanks in advance!

Upvotes: 0

Views: 655

Answers (1)

Anton Protopopov
Anton Protopopov

Reputation: 31672

You could try iloc or ix methods of dataframe from column:

In [140]: df.COL1.iloc[0]
Out[140]: 'A'

In [141]: df.COL1.ix[0]
Out[141]: 'A'

If you need to extract from dataframe you could do iloc[0][0]:

In [145]: df.iloc[0]
Out[145]: 
COL1    A
Name: 0, dtype: object

In [146]: df.iloc[0][0]
Out[146]: 'A'

You could also use iat method which is faster:

In [151]: df.COL1.iat[0]
Out[151]: 'A'

Upvotes: 1

Related Questions