Home > OS >  Is there a way to have spaces in f-string?
Is there a way to have spaces in f-string?

Time:05-10

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?

CodePudding user response:

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}"

CodePudding user response:

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()
  • Related