Home > other >  How to convert month number to month name in an array
How to convert month number to month name in an array

Time:03-21

Hello I'm a beginner at using python.

I was trying to convert a specific array "X" (with a size of 1 column and 153 rows) which contain numbers that represent months (eg: "5" "5" "6" etc..)

I was trying to convert it by importing calendar but I'm not even sure if what I'm doing is right

code goes like this,

import calendar

Y = calendar.month_name[X[:]]

where X is an array of 1 column with multiple rows

I know it might be a stupid error but as I've said, I just started to learn python and I would really appreciate any help.

Thanks in advance!

CodePudding user response:

If I understand your problem correctly, you are getting an error stating: "list indices must be integers or slices, not list". To circumvent this issue, try:

import calendar
X=[1,2,3]

def int_to_month(x):
    return calendar.month_name[x]

    
Y = [int_to_month(x) for x in X[:]]

This way you can return the month_name for each element in your X list.

The above script should return: ['January', 'February', 'March']

EDIT:

If X is a pandas Series, you may convert it to a list using the to_list method:

import calendar
import pandas as pd

mycolumn1=[1, 2, 3]
mycolumn2=["foo", "bar", "foo"]

mydata = {"col1":mycolumn1, "col2":mycolumn2}
df=pd.DataFrame(data=mydata)

X = df['col1'].to_list()

def int_to_month(x):
    return calendar.month_name[x]

    
Y = [int_to_month(x) for x in X[:]]
  • Related