Home > other >  Get the data from a dataframe
Get the data from a dataframe

Time:12-28

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: Clue\n0 Action done while saying "Good dog" Crossword Clue.

but I want:

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

CodePudding user response:

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"        

CodePudding user response:

Another approach is

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

which returns what you wanted

  • Related