How do I convert a column having month in a dataframe to alphabetical numbers (not numeric) based on a specific condition

Viewed 70

I have a dataframe in which a column contains months.

I want to update values of months with alphabetical numbers (one, two, three, etc and not 1,2,3 etc) Is there any library that I can use to make this conversion for the entire column?

P.S. - The column contains more than 1200 rows so there's no point doing it manually.

2 Answers

There is no library which will do this automatically for you. You have to give values for each month, since you mentioned you have month 'names' and not numbers. try this:

df['arrival_date_month'] = df['arrival_date_month'].str[:3]
df.loc[df["arrival_date_month"] == "Jan", 'arrival_date_month'] = 'One'
df.loc[df["arrival_date_month"] == "Feb", 'arrival_date_month'] = 'Two'
df.loc[df["arrival_date_month"] == "Mar", 'arrival_date_month'] = 'Three'
df.loc[df["arrival_date_month"] == "Apr", 'arrival_date_month'] = 'Four'
df.loc[df["arrival_date_month"] == "May", 'arrival_date_month'] = 'Five'
df.loc[df["arrival_date_month"] == "Jun", 'arrival_date_month'] = 'Six'
df.loc[df["arrival_date_month"] == "Jul", 'arrival_date_month'] = 'Seven'
df.loc[df["arrival_date_month"] == "Aug", 'arrival_date_month'] = 'Eight'
df.loc[df["arrival_date_month"] == "Sep", 'arrival_date_month'] = 'Nine'
df.loc[df["arrival_date_month"] == "Oct", 'arrival_date_month'] = 'Ten'
df.loc[df["arrival_date_month"] == "Nov", 'arrival_date_month'] = 'Eleven'
df.loc[df["arrival_date_month"] == "Dec", 'arrival_date_month'] = 'Twelve'

Fun Fact: Here you can play with the conditions too if you want to set the value based on some condition. Try replacing == "Jan" with some other condition too.

Cheers!

Use Series.map with dictionary:

s = pd.to_datetime([1,2,3,4,5,6,7,8,9,10,11,12], format='%m').strftime('%b')
df = pd.DataFrame({'months': s})


d = {'Jan': 'One', 'Feb': 'Two', 'Mar': 'Three', 
     'Apr': 'Four', 'May': 'Five', 
     'Jun': 'Six', 'Jul': 'Seven', 'Aug': 'Eight',
     'Sep': 'Nine', 'Oct': 'Ten', 'Nov': 'Eleven', 'Dec': 'Twelve'}

df['months1'] = df['months'].map(d)
print (df)
   months months1
0     Jan     One
1     Feb     Two
2     Mar   Three
3     Apr    Four
4     May    Five
5     Jun     Six
6     Jul   Seven
7     Aug   Eight
8     Sep    Nine
9     Oct     Ten
10    Nov  Eleven
11    Dec  Twelve
Related