python - 在时间序列预测中将对象类型转换为日期时间

标签 python pandas numpy datetime time-series

我正在研究时间序列,因此我想将对象类型转换为日期时间。我有一个像这样的数据框:

   trxyear  trxmonth
0   2014    JUL-13
1   2014    JUL-13
2   2014    JUL-13
3   2014    JUL-13
4   2014    JUL-13
... ... ...
46394   2023    SEP-22
46395   2023    SEP-22
46396   2023    SEP-22
46397   2023    SEP-22
46398   2023    SEP-22

我想将 trxmonth 转换为日期时间,以便我可以应用时间序列。但是当我使用此代码进行转换时

代码:

from dateutil import parser
print(parser.parse("JUL-13")) 

输出: 2022-07-13 00:00:00

但它可以将 July 2013 转换为 13 July 2022

代码:

print(parser.parse("01-JUL-13") )

输出: 2013-07-01 00:00:00

当我使用此代码时,它可以正确转换,但我的数据不是这种格式。 只是我想转换 JUL-13 --> 01-07-2013

最佳答案

使用to_datetime使用 format 参数:

df['trxmonth'] = pd.to_datetime(df['trxmonth'], format='%b-%y')

print (df)
       trxyear   trxmonth
0         2014 2013-07-01
1         2014 2013-07-01
2         2014 2013-07-01
3         2014 2013-07-01
4         2014 2013-07-01
46394     2023 2022-09-01
46395     2023 2022-09-01
46396     2023 2022-09-01
46397     2023 2022-09-01
46398     2023 2022-09-01

关于python - 在时间序列预测中将对象类型转换为日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73725847/

相关文章:

Python - slice([1,2,3]) 如何工作以及 slice(None, [1, 3], None) 代表什么?

python - 通过组合文本 pandas 制作新的数据框

python - 如何将带有日期时间的 DataFrame 列拆分为两列 : one with dates and one with times of the day?

python - python中两个值之间的指数增长

python - 枚举两个大数组的快速方法?

python - 如何从 Pyspark RDD 中删除空行

python - 吉普错误!堆栈错误 : Can't find Python executable

python - 使用 iloc 进行 Pandas 复制无法按预期工作

python - 如何将一系列索引/类别转换为分类数组

python - 从递归函数返回字典