蟒蛇& pandas :将列组合成一个日期 [英] Python & Pandas: Combine columns into a date

查看:42
本文介绍了蟒蛇& pandas :将列组合成一个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 dataframe 中,时间分为 3 列:yearmonthday,例如这:

In my dataframe, the time is separated in 3 columns: year, month, day, like this:

如何将它们转换为date,以便进行时间序列分析?

How can I convert them into date, so I can do time series analysis?

我可以这样做:

df.apply(lambda x:'%s %s %s' % (x['year'],x['month'], x['day']),axis=1)

给出:

1095       1954 1 1
1096       1954 1 2
1097       1954 1 3
1098       1954 1 4
1099       1954 1 5
1100       1954 1 6
1101       1954 1 7
1102       1954 1 8
1103       1954 1 9
1104      1954 1 10
1105      1954 1 11
1106      1954 1 12
1107      1954 1 13

但是接下来呢?

这就是我最终的结果:

from datetime import datetime
df['date']= df.apply(lambda x:datetime.strptime("{0} {1} {2}".format(x['year'],x['month'], x['day']), "%Y %m %d"),axis=1)
df.index= df['date']

推荐答案

以下是将值转换为时间的方法:

Here's how to convert value to time:

import datetime


df.apply(lambda x:datetime.strptime("{0} {1} {2} 00:00:00".format(x['year'],x['month'], x['day']), "%Y %m %d %H:%M:%S"),axis=1)

这篇关于蟒蛇& pandas :将列组合成一个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆