我有一本词典,其中有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
我该如何迫使时间崩溃,从而摆脱所有难关呢?
答案 0 :(得分:2)
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)