Get year, month or day from numpy datetime64

前端 未结 10 1105
北恋
北恋 2020-12-01 04:13

I have an array of datetime64 type:

dates = np.datetime64([\'2010-10-17\', \'2011-05-13\', \"2012-01-15\"])

Is there a better way than loop

10条回答
  •  悲哀的现实
    2020-12-01 04:46

    I find the following tricks give between 2x and 4x speed increase versus the pandas method described above (i.e. pd.DatetimeIndex(dates).year etc.). The speed of [dt.year for dt in dates.astype(object)] I find to be similar to the pandas method. Also these tricks can be applied directly to ndarrays of any shape (2D, 3D etc.)

    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
    

提交回复
热议问题