从numpy datetime64获取年,月或日

ene*_*ene 51 python datetime numpy

我有一个datetime64类型的数组:

dates = np.datetime64(['2010-10-17', '2011-05-13', "2012-01-15"])
Run Code Online (Sandbox Code Playgroud)

有没有比循环遍历每个元素更好的方法来获得np.array年:

years = f(dates)
#output:
array([2010, 2011, 2012], dtype=int8) #or dtype = string
Run Code Online (Sandbox Code Playgroud)

我正在使用稳定的numpy版本1.6.2.

bmu*_*bmu 38

由于日期时间在numpy中不稳定,我会使用pandas:

In [52]: import pandas as pd

In [53]: dates = pd.DatetimeIndex(['2010-10-17', '2011-05-13', "2012-01-15"])

In [54]: dates.year
Out[54]: array([2010, 2011, 2012], dtype=int32)
Run Code Online (Sandbox Code Playgroud)

熊猫在内部使用numpy日期时间,但似乎避免了numpy到目前为止的短缺.

  • 这给了我错误的结果,numpy 1.7.1和pandas 0.12.0.但是,`Series(dates).apply(lambda x:x.month)`似乎有效. (4认同)

小智 25

我发现以下技巧与上述熊猫方法(即pd.DatetimeIndex(dates).year等)相比,速度提高了2倍和4倍.[dt.year for dt in dates.astype(object)]我发现速度与熊猫方法类似.这些技巧也可以直接应用于任何形状的ndarray(2D,3D等)

dates = np.arange(np.datetime64('2000-01-01'), np.datetime64('2010-01-01'))
years = dates.astype('datetime64[Y]').astype(int) + 1970
months = dates.astype('datetime64[M]').astype(int) % 12 + 1
days = dates - dates.astype('datetime64[M]') + 1
Run Code Online (Sandbox Code Playgroud)

  • 感谢您实际给出答案,而不是说“您不应该使用 <X>,而是使用 <Y>”。 (5认同)
  • 这是一个很好的解决方案。如果 numpy 中有这样简单的东西那就太好了。 (4认同)
  • 作为对@flexatone的回应,你的建议对我不起作用,但这确实有效:`(dates.astype('datetime64[D]') -dates.astype('datetime64[M]')).astype(int) + 1` (3认同)
  • 要获取整数而不是上面“days”示例中的“timedelta64[D]”,请使用:“(dates -dates.astype('datetime64[M]')).astype(int) + 1” (2认同)

RBF*_*F06 11

我就是这样做的。

import numpy as np

def dt2cal(dt):
    """
    Convert array of datetime64 to a calendar array of year, month, day, hour,
    minute, seconds, microsecond with these quantites indexed on the last axis.

    Parameters
    ----------
    dt : datetime64 array (...)
        numpy.ndarray of datetimes of arbitrary shape

    Returns
    -------
    cal : uint32 array (..., 7)
        calendar array with last axis representing year, month, day, hour,
        minute, second, microsecond
    """

    # allocate output 
    out = np.empty(dt.shape + (7,), dtype="u4")
    # decompose calendar floors
    Y, M, D, h, m, s = [dt.astype(f"M8[{x}]") for x in "YMDhms"]
    out[..., 0] = Y + 1970 # Gregorian Year
    out[..., 1] = (M - Y) + 1 # month
    out[..., 2] = (D - M) + 1 # dat
    out[..., 3] = (dt - D).astype("m8[h]") # hour
    out[..., 4] = (dt - h).astype("m8[m]") # minute
    out[..., 5] = (dt - m).astype("m8[s]") # second
    out[..., 6] = (dt - s).astype("m8[us]") # microsecond
    return out
Run Code Online (Sandbox Code Playgroud)

它在任意输入维度上进行矢量化,速度快,直观,适用于 numpy v1.15.4,不使用熊猫。

真的希望 numpy 支持这个功能,它在应用程序开发中一直是必需的。当我必须像这样滚动自己的东西时,我总是感到非常紧张,我总是觉得我错过了一个边缘案例。

  • 功能优良。老实说,可能值得在 numpy github 页面上提交 PR。 (2认同)

Ste*_*ist 10

使用 numpy 1.10.4 版和 Pandas 0.17.1 版,

dates = np.array(['2010-10-17', '2011-05-13', '2012-01-15'], dtype=np.datetime64)
pd.to_datetime(dates).year
Run Code Online (Sandbox Code Playgroud)

我得到你要找的东西:

array([2010, 2011, 2012], dtype=int32)
Run Code Online (Sandbox Code Playgroud)


Nic*_*ick 9

应该有一种更简单的方法来执行此操作,但是,根据您要执行的操作,最佳路径可能是转换为常规Python日期时间对象:

datetime64Obj = np.datetime64('2002-07-04T02:55:41-0700')
print datetime64Obj.astype(object).year
# 2002
print datetime64Obj.astype(object).day
# 4
Run Code Online (Sandbox Code Playgroud)

根据下面的评论,这似乎只适用于Python 2.7.x而不是Python 3.x.

  • 这在python 3.5中不起作用 - "AttributeError:'int'对象没有属性'year'.我也不确定为什么应该在2.7中工作,为什么`.astype(object)`转换为`datetime.datetime`? (3认同)
  • 看来日期时间必须是“datetime[D]”类型,而不是“datetime[ns]”类型。例如,在Python 3.8.12中,`np.datetime64('2001-01-01').astype(object)`给出一个`datetime`对象,但是`np.datetime64('2001-01-01')。 astype('datetime64[ns]').astype(object)` 给出一个 `long`,其中用 `datetime` 替换 `object` 会得到相同的结果。 (3认同)

Mah*_*ahé 5

使用dates.tolist()转换为本机日期时间对象,然后只需访问year. 例子:

>>> dates = np.array(['2010-10-17', '2011-05-13', '2012-01-15'], dtype='datetime64')
>>> [x.year for x in dates.tolist()]
[2010, 2011, 2012]
Run Code Online (Sandbox Code Playgroud)

这基本上与/sf/answers/2469728061/中公开的想法相同,但使用更简单的语法。

使用 python 3.6 / numpy 1.18 进行测试。

编辑:有时需要转换为“datetime64[D]”,例如。当数组的类型为“datetime64[ns]”时。dates.tolist()将上面替换为dates.astype("datetime64[D]").tolist()