【问题标题】:Converting an array of df.index dtype='datetime64[ns]' to Date将 df.index dtype='datetime64[ns]' 数组转换为 Date
【发布时间】:2019-05-22 20:16:38
【问题描述】:

我正在使用pd.Grouper 以 3 天的频率对时间序列进行分组。要检索时间数组,我使用 date = df.index.values 它返回一个时间数组,如下所示:

array(['2010-01-31T00:00:00.000000000', '2010-02-03T00:00:00.000000000',
   '2017-05-12T00:00:00.000000000', '2017-05-15T00:00:00.000000000',
   '2017-05-18T00:00:00.000000000', '2017-05-21T00:00:00.000000000',
   '2017-05-24T00:00:00.000000000', '2017-05-27T00:00:00.000000000',
   '2017-05-30T00:00:00.000000000', '2017-06-02T00:00:00.000000000',
   '2017-06-05T00:00:00.000000000', '2017-06-08T00:00:00.000000000',
   '2017-06-11T00:00:00.000000000', '2017-06-14T00:00:00.000000000',
   '2017-06-17T00:00:00.000000000', '2017-06-20T00:00:00.000000000',
   '2017-06-23T00:00:00.000000000', '2017-06-26T00:00:00.000000000',
   '2017-06-29T00:00:00.000000000', '2017-07-02T00:00:00.000000000',
   '2017-07-05T00:00:00.000000000', '2017-07-08T00:00:00.000000000',
   '2017-07-11T00:00:00.000000000', '2017-07-14T00:00:00.000000000',
   '2017-07-17T00:00:00.000000000', '2017-07-20T00:00:00.000000000',
   '2017-07-23T00:00:00.000000000', '2017-07-26T00:00:00.000000000',
   '2017-07-29T00:00:00.000000000', '2017-08-01T00:00:00.000000000',
   '2017-08-04T00:00:00.000000000', '2017-08-07T00:00:00.000000000'],
  dtype='datetime64[ns]')

我一直在努力寻找正确的日期(最终摆脱 MJD)。当我复制该数组的 1-2 个元素并执行此操作时,它可以工作;

times =['2010-02-03T00:00:00.000000000','2010-02-03T00:00:00.000000000']
t = Time(times, format='isot', scale='utc') 
print(t.mjd)
>>[55230. 55230.]

但是,我无法对整个数组使用相同类型的代码

from astropy.time import Time
t = Time(date, format='isot', scale='utc') 
print(t.mjd)

它给了我一个错误“输入值与格式类 isot 不匹配”。所以,我猜想 Time 需要列表而不是数组,但是将 Date 更改为 list 并不能解决问题。我无法解决,上面的示例是 2 个字符串的列表,它工作正常。我在这里做错了什么?我尝试了其他几种使用 pandas 并尝试循环元素的方法。谢谢您的帮助。 阿比

【问题讨论】:

    标签: python pandas astropy


    【解决方案1】:

    在查看this link之后找到了一种方法

    from astropy.time import Time
    date = df.index.values
    a= []
    for i in [x for x in date]:
        ts = pd.to_datetime(str(i)) 
        d = ts.strftime('%Y-%m-%d')
        a.append(d)
        print(d)
    
    grouped_date = Time(a, format='iso', out_subfmt='date')
    grouped_date_mjd = grouped_date.mjd
    
    print(a[0:3], grouped_date_mjd[0:3])
    >> ['2010-01-31', '2010-02-03', '2010-02-06'] [55227. 55230. 55233.]
    

    【讨论】:

    • 从 astropy 3.1 开始支持np.datetime64 类型的数组输入。
    【解决方案2】:

    由于 astropy 3.1 内置了对 datetime64 的支持,因此您可以简单地这样做:

    In [2]: dates = np.array(['2010-01-31T00:00:00', '2010-02-03T00:00:00'],
       ...:   dtype='datetime64[ns]')
       ...:   
    
    In [3]: tm = Time(dates)
    
    In [4]: tm.mjd
    Out[4]: array([55227., 55230.])
    

    【讨论】:

      猜你喜欢
      • 2022-08-15
      • 2021-09-27
      • 1970-01-01
      • 2020-11-05
      • 2021-10-01
      • 2020-04-28
      • 2019-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多