gpt4 book ai didi

python - 将 numpy 数组转换为日期时间列表

转载 作者:太空狗 更新时间:2023-10-30 00:05:38 24 4
gpt4 key购买 nike

我有一个二维日期数组,格式如下:

[Y Y Y ... ]
[M M M ... ]
[D D D ... ]
[H H H ... ]
[M M M ... ]
[S S S ... ]

看起来像

data = np.array([
[2015, 2015, 2015, 2015, 2015, 2015], # ...
[ 1, 1, 1, 1, 1, 1],
[ 1, 1, 1, 2, 2, 2],
[ 23, 23, 23, 0, 0, 0],
[ 4, 5, 5, 37, 37, 37],
[ 59, 1, 2, 25, 27, 29]
])

将其转换为一个日期时间对象列表的最佳方法是什么?

最佳答案

import datetime
import numpy as np

data = np.array(
[[2015, 2015, 2015, 2015, 2015, 2015],
[ 1, 1, 1, 1, 1, 1],
[ 1, 1, 1, 2, 2, 2],
[ 23, 23, 23, 0, 0, 0],
[ 4, 5, 5, 37, 37, 37],
[ 59, 1, 2, 25, 27, 29]]
)

# Transpose the data so that columns become rows.
data = data.T

# A simple list comprehension does the trick, '*' making sure
# the values are unpacked for 'datetime.datetime'.
new_data = [datetime.datetime(*x) for x in data]

print(new_data)

[datetime.datetime(2015, 1, 1, 23, 4, 59), datetime.datetime(2015, 1, 1, 23, 5, 1), datetime.datetime(2015, 1, 1, 23, 5, 2), datetime.datetime(2015, 1, 2, 0, 37, 25), datetime.datetime(2015, 1, 2, 0, 37, 27), datetime.datetime(2015, 1, 2, 0, 37, 29)]

关于python - 将 numpy 数组转换为日期时间列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40165223/

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