首页 > 解决方案 > 熊猫重采样不会改变时间增量

问题描述

我有一本字典,其中有 4 个不同的键,代表不同的作物(玉米、大豆、冬小麦和春小麦)。每个键都有 10 个不同的数据数组作为字典中的值(温度、24 小时温度变化等)。然后我想从数据中创建两个新字典,从 24 小时变化值中分离出实际值(如温度、降水)。数据为 6 小时一次。

corn=glob.glob('/Users/eli/Documents/Python_data/plotly_practice/20200812_00/20200812_00_ec_ens_*'+'corn'+'_timeseries.nc')
soybean=glob.glob('/Users/eli/Documents/Python_data/plotly_practice/20200812_00/20200812_00_ec_ens_*'+'soybeans'+'_timeseries.nc')
winterwheat=glob.glob('/Users/eli/Documents/Python_data/plotly_practice/20200812_00/20200812_00_ec_ens_*'+'winterwheat'+'_timeseries.nc')
springwheat=glob.glob('/Users/eli/Documents/Python_data/plotly_practice/20200812_00/20200812_00_ec_ens_*'+'springwheat'+'_timeseries.nc')
all_files=[corn, soybean,winterwheat,springwheat]

crop_names=['corn', 'soybeans', 'winterwheat', 'springwheat']
data={}
for i in crop_names:
    for j in all_files:
        data[i]=xr.open_mfdataset(j)

我创建了两个空字典,然后遍历键。

today=dt.date.today()
df_vals={}
df_deltas={}
for i in data.keys():

接下来,我填写df_vals.

    df_vals[str(i)]=data[i].to_dataframe().reset_index()
    df_vals[i]['time']=pd.date_range((today-dt.timedelta(days=1)), (today+dt.timedelta(days=14)), freq='6H')

然后,我想填写df_deltas. 但是,我想做这个有点不同。对于三角洲,我担心 24 小时的变化,因此我需要应用滚动平均值或总和,具体取决于变量是温度还是降水量。

    df_deltas[i]=df_vals[i].filter(regex='delta')
    df_deltas[i]['time']=pd.date_range((today-dt.timedelta(days=1)), (today+dt.timedelta(days=14)), freq='6H')
    df_deltas[i]=df_deltas[i].set_index('time')
    df_deltas[i].loc[:, df_deltas[i].columns.str.contains('precip')]=df_deltas[i].resample('24H').sum()
    df_deltas[i].loc[:, df_deltas[i].columns.str.contains('temp')]=df_deltas[i].resample('24H').mean()
    df_deltas[i]=df_deltas[i].reset_index()

虽然计算正确完成,但更新的数据帧不会缩减时间。这是一种作物的产量。

df_deltas['corn]

time    2m_temp_24hdelta_prod   2m_temp_24hdelta_area   total_precip_24hdelta_prod  total_precip_24hdelta_area
0   2020-08-13 00:00:00 0.228715    0.161631    -0.650041   -0.552645
1   2020-08-13 06:00:00 NaN NaN NaN NaN
2   2020-08-13 12:00:00 NaN NaN NaN NaN
3   2020-08-13 18:00:00 NaN NaN NaN NaN
4   2020-08-14 00:00:00 0.676321    0.214109    -1.312289   -1.020344

我如何迫使时间崩溃,从而摆脱所有的nans?

标签: pythonpandasdataframedatetime

解决方案


resampled_df = df_deltas[['precip','temp']].resample('24h').agg({'precip':'sum','temp':'mean'})

您需要让 df 中的所有系列具有相同的索引

你可以改为做类似的事情

interesting_cols = [c for c in df_deltas.columns if "precip" in c or "temp" in c]
aggs = {c:'sum' if 'precip' in c else 'mean' for c in interesting_cols}
df_deltas[columns].resample('24h').agg(aggs)

推荐阅读