xarray/datetime64 [ns]:从datetime移除或规范化时间 [英] xarray/datetime64[ns]: remove or normalise time from datetime

查看:659
本文介绍了xarray/datetime64 [ns]:从datetime移除或规范化时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个坐标为'time'的数据数组arr. arr:

I have a data array arr with coordinate 'time'. arr:

    <xarray.DataArray 'T' (time: 731)>
array([244.40161, 244.39998, ..., 244.40936, 244.40549], dtype=float32)
Coordinates:
  * time         (time) datetime64[ns] 1979-01-01T09:00:00 ... 1980-12-31T09:00:00

提取前5个时间坐标arr.time.values[:5]:

array(['1979-01-01T09:00:00.000000000', '1979-01-02T09:00:00.000000000',
       '1979-01-03T09:00:00.000000000', '1979-01-04T09:00:00.000000000',
       '1979-01-05T09:00:00.000000000'], dtype='datetime64[ns]')

我希望日期时间的格式为'1979-01-01''1979-01-02'等,而没有时间,或者将时间标准化为00:00:00.

I want the format of my date-time to just be '1979-01-01', '1979-01-02' etc. without the time, or normalise the time at 00:00:00.

对于熊猫数据框有一些解决方案,但由于功能不适用,我不太确定如何在此处应用它们(使用pandas.to_datetime时仅保留日期部分)

There are some solutions for pandas data frame but I'm not quite sure how to apply them here since the functions aren't applicable (Converting between datetime, Timestamp and datetime64, Keep only date part when using pandas.to_datetime)

推荐答案

有几种方法可以做到这一点.我经常使用的快速而肮脏的方法是使用重采样:

There are a few ways you can do this. The quick and dirty way I often use is uses resample:

da.resample(time='1D').first()

更健壮的方法是直接修改时间索引:

Something that is a bit more robust would be modify the time index directly:

da['time'] = da.indexes['time'].normalize()

最后,通常可以通过创建新的日期时间索引来完成此操作:

Finally, this can be done generally by creating a new datetime index:

da['time'] = pd.date_range(da['time'][0], periods=len(da['time']), freq='1D')

请注意,第二个和第三个示例在计算上将比第一个便宜,但确实需要直接使用基础Pandas索引.

Note that the second and third examples are going to be computationally cheaper than the first but does require working directly with the underling Pandas index.

这篇关于xarray/datetime64 [ns]:从datetime移除或规范化时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆