Replacing an integer by looking at a dictionary - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Replacing an integer by looking at a dictionary (/thread-17950.html) |
Replacing an integer by looking at a dictionary - wendysling - Apr-30-2019 Hi, I am trying to find the current month in a dataframe to pull other information from that specific month. Datetime provides the month as a number. However, my dataframe has columns with the Month as a text (Jan, Feb, etc.) How can I convert the value from datetime (= int) to the month's text so I can pull the month's information? Or is there a better way to do this? (BTW, I ended up modifying my dataframe and naming the columns by numbers, instead of texts. But I will need to do the same thing again, and changing the header all the time is not feasible.) Here is what I tried, but I keep receiving an error "TypeError: 'int' object is not iterable". Thank you for your help! #Create date now = datetime.datetime.now() #Create a variable with today's date day = now.day month = now.month year = now.year dict_month = {1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'} def replace_month(currentmonth,dictionary): for item in month: if item in dictionary.keys(): currentmonth = currentmonth.replace(item,dictionary[item]) return currentmonth replace_month(month,dict_month)OUTPUT
RE: Replacing an integer by looking at a dictionary - Larz60+ - Apr-30-2019 import datetime today = datetime.datetime.today() print('ISO :', today) print('Month: {:%b}'.format(today))output:
RE: Replacing an integer by looking at a dictionary - nilamo - Apr-30-2019 return dictionary[currentmonth] ?
RE: Replacing an integer by looking at a dictionary - wendysling - May-02-2019 This is helpful to change the number for a text. |