【问题标题】:write Pandas DatetimeIndex to netCDF variable将 Pandas DatetimeIndex 写入 netCDF 变量
【发布时间】:2023-04-01 08:45:02
【问题描述】:

我正在尝试将时间序列的日期写入 netCDF 变量。我的日期存储为名为 date_array 的 Pandas DatetimeIndex。我正在尝试使用的代码如下:

Times = w_nc_fid.createVariable('Times','S1',('time',))
Times[:] = str(date_array)

结果是一个 [72,1] 数组,其中只有字符串 D。我实际上要写的是日期字符串(连续 72 个日期):

'2015-07-19 10:00:00'
'2015-07-19 11:00:00'
'2015-07-19 12:00:00'

谁能帮我解决这个问题?

【问题讨论】:

  • 您是否有理由将日期写为字符串而不是浮点数?通常,netCDF 中的时间存储为自参考时间以来的时间数组(例如“自 1970-01-01”)。

标签: python netcdf


【解决方案1】:

使用netCDF4,可以通过以下方式完成:

import numpy as np
import netCDF4

times = np.array(['2015-07-19 10:00:00', '2015-07-19 11:00:00', '2015-07-19 12:00:00'], dtype=object)

fileout = netCDF4.Dataset('./string_out.nc', 'w')
fileout.createDimension('time', len(times))
times_out = fileout.createVariable('times', str, 'time',)
times_out[:] = times
fileout.close()

您可以使用 ncks/ncdump 确认:

>>> ncks string_out.nc | more
...
time[0] times[0]=2015-07-19 10:00:00 
time[1] times[1]=2015-07-19 11:00:00 
time[2] times[2]=2015-07-19 12:00:00 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-27
    • 2013-05-14
    • 1970-01-01
    • 2018-03-10
    • 2012-11-26
    • 2020-10-04
    • 1970-01-01
    • 2021-12-06
    相关资源
    最近更新 更多