Vectorized year/month/day operations with NumPy datetime64

前端 未结 3 1440
梦如初夏
梦如初夏 2021-01-05 06:06

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 year

3条回答
  •  有刺的猬
    2021-01-05 06:33

    I don't know of a way to do it without some sort of looping, but I inlined it a bit with a list comprehension:

    years = [1990, 1992, 1995, 1994]
    months = [1, 6, 3, 7]
    days = [3, 20, 14, 27]
    np.array(['{0[0]}-{0[1]}-{0[2]}'.format(x) for x in zip(years, months, days)], dtype='datetime64')
    

    Going back the other way, you have to convert each item to a regular datetime. You can do this by calling astype(object), which works for the whole array or for individual objects. Which one you do probably depends on how your using the data.

提交回复
热议问题