How can I use f string to call a list index?

I’ve read this issue, but it didn’t work here. I’ve a dataframe and want to add new column with the month index considering the position they’ve in a list.

I don’t want to create an if condition because I’ve more languages in real life. That’s why I want to use f string to call my list. But it isn’t working.

Here is the example:

dic_events = {'month':['January', 'February'], 'url':['', '']}

df_events = pd.DataFrame(dic_events)

def add_month_index(language, month):
  month_en = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
  month_de = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"]
  df_events['month_id'] = f"month_{language}".index(f"{month}") + 1
  return df_events

add_month_index('en', 'January')

>Solution :

Use a dictionary that maps the language to the list of month names.

def add_month_index(language, month):
  months = {
      "en": ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
      "de": ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"]
  df_events['month_id'] = months[language].index(month) + 1
  return df_events

I’m not sure why month is a parameter to the function. It seems like you would actually want to get that from the month column of the df, so each row of the table will get the month ID corresponding to its month, rather than assigning the same month ID to every row.

Leave a Reply