1
我有一个区域类型的字典,在每个子区域的字典内,以及每个这样一个熊猫数据框对象中,这些对象被索引到我需要计算每个参数(列)时间序列的时间段。另外,我需要它在两个单位。如何在嵌套字典中通过元素访问pandas multiindex?
所以我创造了这样的事情:
regions = ['region_x', 'region_y']
sub_regions = ['a', 'b', 'c']
parameters = ['x', 'y', 'z']
units = ['af', 'cbm']
start = datetime(2000, 01, 01)
end = datetime(2000, 01, 03)
arrays = [parameters * 2, units * 3]
cols = pd.MultiIndex.from_arrays(arrays)
empty_df = pd.DataFrame(index=pd.date_range(start, end), columns=cols).fillna(0.0)
tab_dict = {}
for region in regions:
tab_dict.update({region: {}})
for sub_region in sub_regions:
tab_dict[region].update({sub_region: empty_df})
它返回
{'region_y':
{'a': x y z x y z
af cbm af cbm af cbm
2000-01-01 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-02 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-03 0.0 0.0 0.0 0.0 0.0 0.0,
'c': x y z x y z
af cbm af cbm af cbm
2000-01-01 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-02 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-03 0.0 0.0 0.0 0.0 0.0 0.0,
'b': x y z x y z
af cbm af cbm af cbm
2000-01-01 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-02 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-03 0.0 0.0 0.0 0.0 0.0 0.0},
'region_x':
{'a': x y z x y z
af cbm af cbm af cbm
2000-01-01 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-02 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-03 0.0 0.0 0.0 0.0 0.0 0.0,
'c': x y z x y z
af cbm af cbm af cbm
2000-01-01 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-02 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-03 0.0 0.0 0.0 0.0 0.0 0.0,
'b': x y z x y z
af cbm af cbm af cbm
2000-01-01 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-02 0.0 0.0 0.0 0.0 0.0 0.0
2000-01-03 0.0 0.0 0.0 0.0 0.0 0.0}}
现在我需要每天从提取的值(用np.random
这里),并以某种方式插入到它的正确的地方。我已成功进入单嵌套字典并更新DataFrame对象(使用dict_[key].loc[date] = x
),但此处的“类似”方法返回SettingWithCopyWarning并且不更新数据帧。
for day in rrule.rrule(rrule.DAILY, dtstart=start, until=end):
for region in regions:
for sub_region in sub_regions:
for parameter in parameters:
for unit in units:
unit_af = np.random.randint(100)
unit_cbm = unit_af * 2
tab_dict[region][sub_region][parameter]['af'].loc[day] = unit_af
tab_dict[region][sub_region][parameter]['cbm'].loc[day] = unit_cbm
它只是返回我开始的事情。我将不胜感激关于如何更新这些值的任何建议。请原谅那些乱七八糟的代码,这是我写的最简单的代码,可以重现我的(更丑陋的)问题。