Python 和 Pandas:将列组合成一个日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31869257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python & Pandas: Combine columns into a date
提问by cqcn1991
In my dataframe, the time is separated in 3 columns: year, month, day, like this:

在 my 中dataframe,时间分为 3 列:year, month, day,如下所示:

How can I convert them into date, so I can do time series analysis?
如何将它们转换为date,以便进行时间序列分析?
I can do this:
我可以做这个:
df.apply(lambda x:'%s %s %s' % (x['year'],x['month'], x['day']),axis=1)
which gives:
这使:
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
But what follows?
但是接下来呢?
EDIT:This is what I end up with:
编辑:这就是我最终的结果:
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']
采纳答案by FirebladeDan
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)
回答by Clément
It makes no sense to format a date to a string and immediately reparse it; use the datetimeconstructor instead:
将日期格式化为字符串并立即重新解析它是没有意义的;改用datetime构造函数:
df.apply(lambda x: datetime.date(x['year'], x['month'], x['day']), axis=1)

