gpt4 book ai didi

python 和 Pandas : Combine columns into a date

转载 作者:太空狗 更新时间:2023-10-29 18:29:34 25 4
gpt4 key购买 nike

在我的 dataframe 中,时间分为 3 列:yearmonthday,例如这个: enter image description here

如何将它们转换成日期,以便进行时间序列分析?

我能做到:

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']

最佳答案

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

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)

关于 python 和 Pandas : Combine columns into a date,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31869257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com