0

I am trying to get the index for a value in a specific column of my DF that is variable and must have spaces in it. I do not have control of the name of this column. I'm using query with f-string. So lets say I have the following.

import pandas as pd
a= 'Jan'
b=str(2022)
title=a+' of '+b
df=pd.DataFrame({title:['Inducts', 'Valid Reads', 'No Reads'],'Monday':[100,90,10],'Tuesday':[110,77,33]})
PlaceinColumn=df.query('Title==Inducts').index.tolist()
print(PlaceinColumn[0])

When I run this I get the following syntax error:

Jan of 2022 ==BACKTICK_QUOTED_STRING_Valid_Reads
    ^

SyntaxError: invalid syntax

Looking into this further it seems I cannot have spaces when using F-string. Is there a way around this beside making a new df out of the title column with a different column name?

Jenn B
  • 1
  • 1

2 Answers2

0

Don't understand where is the mistake ? and for the f string :

import pandas as pd
a= 'Jan'
b=str(2022)
title=f"{a} of {b}"
DataSciRookie
  • 798
  • 1
  • 3
  • 12
  • Sorry I had copied in the piece of code I used to verify where my error was instead of the one throwing the error. I fixed it. – Jenn B May 09 '22 at 18:13
  • @JennB could you close the question please and vote for something useful if you want thank you – DataSciRookie May 09 '22 at 18:30
0

Check the doc of df.query

column names containing spaces or punctuations (besides underscores) or starting with digits must be surrounded by backticks.

PlaceinColumn=df.query(f'`{title}`=="Inducts"').index.tolist()
Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52