pythonpandas

Convert month abbreviation to full name


I have this function which converts an English month to a French month:

def changeMonth(month):
    global CurrentMonth
    match month:
        case "Jan":
            return "Janvier"
        case "Feb":
            return "Février"
        case "Mar":
            return "Mars"
        case "Apr":
            return "Avril"
        case "May":
            return "Mai"
        case "Jun":
            return "Juin"
        case "Jul":
            return "Juillet"
        case "Aug":
            return "Août"
        case "Sep":
            return "Septembre"
        case "Oct":
            return "Octobre"
        case "Nov":
            return "Novembre"
        case "Dec":
            return "Décembre"

        # If an exact match is not confirmed, this last case will be used if provided
        case _:
            return ""

and I have a pandas col df["month"]= df['ic_graph']['month'].tolist():

enter image description here

now what I'm looking for is to pass the df["month"] col through the changeMonth function to display the df["month"] in frensh months

By the way, I do not want to use the

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'fr_FR')

Solution

  • Question seems a bit unclear to me,
    Do you want to replace the month column in dataframe itself?
    If yes something like this can work:

    def changeMonth(month):
        if month=="Jan":
                return "Janvier"
        elif month=="Feb":
                return "Février"
        elif month=="Mar":
            return "Mars"
        elif month=="Apr":
            return "Avril"
        elif month=="May":
            return "Mai"
        elif month=="Jun":
            return "Juin"
        elif month=="Jul":
            return "Juillet"
        elif month=="Aug":
            return "Août"
        elif month=="Sep":
            return "Septembre"
        elif month=="Oct":
            return "Octobre"
        elif month=="Nov":
            return "Novembre"
        elif "Dec":
                return "Décembre"
    
        # If an exact match is not confirmed, this last case will be used if provided
        else:
            return ""
    
    df['month']=df['month'].apply(changeMonth)
    
    

    But if you want to change the month while just printing the list out, you can use list comprehension,

    french_month_list = [changeMonth(i) for i in df['ic_graph']['month'].tolist()]