Sheyanoff
Sheyanoff

Reputation: 63

Pandas replace months names within dataframe values

I have dataset where months are like 'January', 'February' etc. For example '23:12 25 April 2016'

The goal is to transform it into '23:12 25 4 2016' using .replace() for the whole dataframe.

Any ideas? Thanks.

UDP. Forgot the main problem: this example has months in english, originally I have them in other language so I need unicode replacement first to to_datetime

Upvotes: 1

Views: 1165

Answers (1)

jezrael
jezrael

Reputation: 862511

IIUC you can use to_datetime for reformating dates in column date:

print df
                  date
0  23:12 25 April 2016

df['date'] = pd.to_datetime(df['date'])
print df

                 date
0 2016-04-25 23:12:00

Another solution is add parameter format:

df['date'] = pd.to_datetime(df['date'], format="%H:%M %d %B %Y")
print df
                 date
0 2016-04-25 23:12:00

If names of months are Russian use replace:

import pandas as pd

df = pd.DataFrame({'date': [u'23:12 25 январь 2016']})

d = {u'январь':'January', u'февраль':'February', u'март':'March'}

df['date'] = df['date'].replace(d, regex=True)

df['date'] = pd.to_datetime(df['date'], format="%H:%M %d %B %Y")
print df
                 date
0 2016-01-25 23:12:00

Upvotes: 2

Related Questions