Pepe
Pepe

Reputation: 484

Converting month number to datetime in pandas

How do I transform a month number (float) to datetime in pandas with a format like 2010-01-01?

    date
0   1.0       
1   2.0       
2   3.0       
3   4.0       
4   5.0 

Expected output:

    date
0   2010-01-01       
1   2010-02-01      
2   2010-03-01      
3   2010-04-01       
4   2010-05-01

Upvotes: 2

Views: 3757

Answers (2)

Vaishali
Vaishali

Reputation: 38415

Append year and month and convert to date time

pd.to_datetime('2010-' + df.date.astype(int).astype(str) + '-1', format = '%Y-%m')

0   2010-01-01
1   2010-02-01
2   2010-03-01
3   2010-04-01
4   2010-05-01

Upvotes: 4

ernest_k
ernest_k

Reputation: 45309

A simple solution can be to just add the year and day columns to the data frame, and call pd.to_datetime(df):

df = df.assign(year=2010, day=1, month=lambda l: l.date.apply(np.int)).drop('date', axis=1)
df['date'] = pd.to_datetime(df)

df = df.drop(['year', 'month', 'day'], axis=1)

print(df)

        date
0 2010-01-01
1 2010-02-01
2 2010-03-01
3 2010-04-01
4 2010-05-01

Upvotes: 0

Related Questions