在pandas中将月号转换为datetime

问题描述 投票:1回答:2

如何使用像2010-01-01这样的格式将ponda中的月份数(浮点数)转换为日期时间?

    date
0   1.0       
1   2.0       
2   3.0       
3   4.0       
4   5.0 

预期产量:

    date
0   2010-01-01       
1   2010-02-01      
2   2010-03-01      
3   2010-04-01       
4   2010-05-01
python pandas
2个回答
1
投票

附加年份和月份并转换为日期时间

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

0
投票

一个简单的解决方案是将yearday列添加到数据框中,并调用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
© www.soinside.com 2019 - 2024. All rights reserved.