-2

How the d.keys() in d can match with the df['month'] to display the d.values?

If let say the dataframe 's data 01/01/2022, 01/02/2022, 01/03/2022, ...etc How the 1 in the df['month'] match with the d.keys() to display Jan?

df['month'] = pd.to_datetime(df['Settlement_Date']).dt.month


d = {1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun',...}
beginofwork
  • 129
  • 8
  • 2
    Could you please include the output of [`dput(df)`](https://stackoverflow.com/questions/49994249/example-of-using-dput) in your question? – Kitswas Aug 12 '22 at 09:27
  • you can do `df["month"].replace(d)` it will replace month numbers with corresponding month value in your dictionary. – Prashant Aug 12 '22 at 09:33

2 Answers2

0

You can map the dictionary to the months -

df = pd.DataFrame(pd.date_range('1-Jan-2022', '1-Jun-2022', freq='M'), columns=['dates'])
d = {1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun'}
df['dates'].dt.month.map(d)

Output

0    Jan
1    Feb
2    Mar
3    Apr
4    May
Name: dates, dtype: object
Mortz
  • 4,654
  • 1
  • 19
  • 35
0

You can use apply function on the data frame. Lets go by your example:

month_labels = {1: 'Jan', 2: 'Feb', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August',9: 'Spet', 10: 'Oct', 11: 'Nov', 12: 'Dec'}

df['month'] = df['date'].dt.month
df['month'].apply(lambda x: month_labels[x])

Also, if you have specific use case of converting number to dates, you can use .dt.month_name() function in pandas.

Sahil Bagnial
  • 116
  • 1
  • 4