0

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':['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')
polo
  • 185
  • 1
  • 3
  • 11
  • What's the goal here? Please show expected output. – Jab Jun 17 '22 at 18:37
  • 4
    A better approach would be to have a dictionary holding your languages - `months = {'en': [...], 'de': [...]}`, then use `months[language]` to choose one of the lists. – jasonharper Jun 17 '22 at 18:38
  • 1
    Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – 0x5453 Jun 17 '22 at 18:40
  • @Jab the expected output is to have a column called 'month_id' in which we should see 1 when the row is related to January. And 2 when it's related to February... – polo Jun 17 '22 at 18:42
  • @0x5453 no, we're creating a new column to the dataframe – polo Jun 17 '22 at 18:43

1 Answers1

1

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612