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

Atharva :

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.

Vignesh :

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!

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=387013&siteId=1