Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

dic_events = {'month':['January', 'February'], 'url':['www.abc.com', 'www.def.com']}

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading