使用 NumPy datetime64 进行矢量化年/月/日操作 [英] Vectorized year/month/day operations with NumPy datetime64
问题描述
我想从年、月和日的一维向量中创建 NumPy datetime64 对象的向量,也可以反向,即从每日 datetime64 向量中提取年、月或日的向量.我使用的是 NumPy 1.7.0b2.
I would like to create vectors of NumPy datetime64 objects from 1-D vectors of years, months, and days, and also go the reverse direction, that is extracting vectors of years, months, or days from a daily datetime64 vector. I'm using NumPy 1.7.0b2.
例如,假设
years = [1990, 1992, 1995, 1994]
months = [1, 6, 3, 7]
days = [3, 20, 14, 27]
现在我想使用这些年、月和日创建一个长度为 4 的 np.datetime64 向量.有没有不使用 Python 循环的方法?
Now I want to create a np.datetime64 vector of length 4 using these years, months, and days. Is there a way without using a Python loop?
换个方向,假设 dates
是数据类型为 np.datetime64 的向量,频率为每天.然后我将能够像 x.DAYS()
那样返回一个向量 [3, 20, 14, 27]
.
Going the other direction, suppose dates
is a vector of datatype np.datetime64 and the frequency is daily. Then I would to be able to something like x.DAYS()
and get back a vector [3, 20, 14, 27]
.
推荐答案
import numpy as np
def compose_date(years, months=1, days=1, weeks=None, hours=None, minutes=None,
seconds=None, milliseconds=None, microseconds=None, nanoseconds=None):
years = np.asarray(years) - 1970
months = np.asarray(months) - 1
days = np.asarray(days) - 1
types = ('<M8[Y]', '<m8[M]', '<m8[D]', '<m8[W]', '<m8[h]',
'<m8[m]', '<m8[s]', '<m8[ms]', '<m8[us]', '<m8[ns]')
vals = (years, months, days, weeks, hours, minutes, seconds,
milliseconds, microseconds, nanoseconds)
return sum(np.asarray(v, dtype=t) for t, v in zip(types, vals)
if v is not None)
years = [1990, 1992, 1995, 1994]
months = [1, 6, 3, 7]
days = [3, 20, 14, 27]
print(compose_date(years, months, days))
收益
array(['1990-01-03', '1992-06-20', '1995-03-14', '1994-07-27'], dtype='datetime64[D]')
这篇关于使用 NumPy datetime64 进行矢量化年/月/日操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!