Get the data from a dataframe

Question:

Word Clue
PAT Action done while saying "Good dog"
RASCALS Mischief-makers
PEN It might click for a writer

I want to take the data from Clue column by Index.

I have used the iloc but I want the data in string format to use it somewhere else, the format it gives it back is not what I want.

x = df.iloc[[0],[1]]

It will show it as a dataframe, and when I use it in the following code it also shows the Clue(Column Name):

y = "The answer for: {} Crossword Clue.".format(x)

Output:

The answer for: Cluen0 Action done while saying "Good dog" Crossword Clue.

but I want:

The answer for: Action done while saying "Good dog" Crossword Clue.
Asked By: Navid Aslankhani

||

Answers:

Just remove the square brackets when using .iloc. When you pass lists as indexes for rows and columns in .iloc, it assumes you are trying to pull multiple rows and columns and returns a DataFrame instead of the value from a single cell as a string, as you are expecting.

x = df.iloc[0,1]    #<----
y = "The answer for: {} Crossword Clue.".format(x)

print(y)
'The answer for: Action done while saying "Good dog" Crossword Clue.'

You can see how pandas reacts to different objects as inputs to the .iloc below

df.iloc[0,1]   #OUTPUT IS STRING

# 'Action done while saying "Good dog"'

#--------------------------------------

df.iloc[0,[1]]   #OUTPUT IS SERIES

#Clue    Action done while saying "Good dog"
#Name: 0, dtype: object

#--------------------------------------


df.iloc[[0],1]   #OUTPUT IS SERIES

#0    Action done while saying "Good dog"
#Name: Clue, dtype: object

#--------------------------------------

df.iloc[[0],[1]]   #OUTPUT IS DATAFRAME

#                                  Clue
#0  Action done while saying "Good dog"        
Answered By: Akshay Sehgal

Another approach is

x = data.iloc[0][1]
y = "The answer for: {str} Crossword Clue".format(str = x)

which returns what you wanted

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.