我有一个表格日期的二维数组:
[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]
])
将此转换为一个日期时间对象列表的最佳方法是什么?
答案 0 :(得分:3)
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)]
答案 1 :(得分:0)
如果你想要np.datetime64
个对象,那么这可行:
import functools
units = 'YMDhms'
first_vals = np.array([1970, 1, 1, 0, 0, 0])
epoch = np.datetime64('1970')
results = functools.reduce(
np.add,
[
d.astype('timedelta64[{}]'.format(unit))
for d, unit in zip(data - first_vals[:,np.newaxis], units)
],
epoch
)
给出了:
array(['2015-01-01T23:04:59',
'2015-01-01T23:05:01',
'2015-01-01T23:05:02',
'2015-01-02T00:37:25',
'2015-01-02T00:37:27',
'2015-01-02T00:37:29'], dtype='datetime64[s]')