获取熊猫数据帧中日期时间索引的时差并重新索引

时间:2021-05-27 23:05:31

标签: python pandas time-series

我正在尝试将 .nc 文件读入 Pandas 数据帧。 nc 文件中的时间戳是我们测量数据的时间间隔的中间值。但是,我想结束时间间隔。所以首先我得到 datetimeindex 中的时差并除以 2 并将其添加到旧时间戳中。然后用新的时间戳重新索引数据。 以下 python 代码的结果非常接近我的预期。但是还有两个问题需要解决。

  1. 如何在秒内避免浮点数并将其四舍五入为整数?

  2. 第一个时间戳是 NaT,有没有办法让它自动显示为日期时间? (应该是 2007-11-30 20:40:09)。

欢迎提出任何建议!

我的python代码:

nc_files_to_open = glob.glob(r'root\*\*\200*.nc', recursive=True)

df = xr.open_mfdataset(nc_files_to_open).to_dataframe()

df.index = df.index + df.index.to_series().diff()/2

'旧'df 的结果:

                         X
time
2007-11-30 20:20:39           6
2007-11-30 20:59:39           5
2007-11-30 21:38:38           4
2007-11-30 22:17:38           3
2007-11-30 22:56:38           2

'new' df 的结果:

                         X
time                                            
NaT                               6
2007-11-30 21:19:09.000           5
2007-11-30 21:58:07.500           4
2007-11-30 22:37:08.000           3
2007-11-30 23:16:08.000           2


print(df.index)


DatetimeIndex(...
dtype='datetime64[ns]', name='time', length=5, freq=None)

1 个答案:

答案 0 :(得分:1)

尝试使用 fillnaceil

df.index = df.index + df.index.to_series().diff()/2
df.index = df.index.fillna(pd.to_datetime('2007-11-30 20:40:09')).ceil(freq='s')  

                        X
time    
2007-11-30 20:40:09     6
2007-11-30 21:19:09     5
2007-11-30 21:58:08     4
2007-11-30 22:37:08     3
2007-11-30 23:16:08     2