将缺少的日期添加到时间序列数据帧

2024-05-12 09:44:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个时间序列数据框,其中包含多个城市的年温度值,但对于一些城市,我缺少一组日期

数据帧示例

ID      Date        City    PRCP    TAVG    TMAX    TMIN
abcd1   2020-01-01  Zurich  0       -1.9    -0.9    -2.9
abcd1   2020-01-02  Zurich  9.1      8.8    12.7    4.9
abcd1   2020-01-03  Zurich  0.8      8.55   13.2    3.9
abcd1   2020-01-04  Zurich  0        4.1    10.8    -2.6

.
.
abcd9   2020-01-01 Singapore 4.1    5.9     0.3     3.1
abcd9   2020-01-04 Singapore 0.32   13.78   4.22    9   
abcd9   2020-01-28 Singapore 9.42   11.32   5.34    8.33
...

现在假设每个月都缺少几个日期,这样Date列中的总天数为300天。我想将剩余的天数添加到dataset中,并将nulls(NaN)分配到TMAX,TMIN..列,以便这些日期的总天数为365天

这就是我现在正在做的

df_list = []

for (columns, group) in df.groupby(['ID', 'City']):
    idx = pd.MultiIndex.from_product([group['ID'].unique(),
                                      pd.date_range(group['Date'].min().replace(day=1), end=group['Date'].max(), freq='D')],
                                     names=['ID', 'Date'])
    group = group.set_index(['ID', 'Date']).reindex(idx).reset_index()
    group['City'] = group['City'].fillna(method='bfill')
    df_list.append(group)

data = pd.concat(df_list, ignore_index=True)

这样做的目的是填充start_indexend_index之间的日期(并为这些日期填充NaN到PRCP、TMIN、TMAX、TAVG),但即使这样,我也会丢失一些日期,即计数不等于365

例如,如果源文件包含10月1日至10月28日的数据,则上述数据将添加此范围内的任何缺失日期,但不会将29、30、31添加到数据集

是否有一种方法可以为我的City列中的所有城市计算从1 Jan31 Dec(年份不相关且忽略闰年)的所有日期


Tags: 数据idcitydfdateindexgrouplist
1条回答
网友
1楼 · 发布于 2024-05-12 09:44:13

可以通过在GroupBy.apply中使用带有DataFrame.reindex的自定义函数,在数据帧中添加缺失的日期,然后重新分配索引:

df['Date'] = pd.to_datetime(df['Date'])

f = lambda x: x.reindex(pd.date_range(pd.to_datetime('2020-01-01'), pd.to_datetime('2020-12-31'), name='date'))
df = df.set_index('Date').groupby(['ID','City']).apply(f).drop(['ID','City'], axis=1)

相关问题 更多 >