Python 如何在嵌套dict中按元素访问多索引?
我有一个区域类型的dict,在每个子区域的dict中,在每个数据帧对象的dict中,索引到我需要计算每个参数(列)时间序列的周期。此外,我需要它在两个单位 所以我创造了这样的东西:Python 如何在嵌套dict中按元素访问多索引?,python,pandas,dictionary,multi-index,Python,Pandas,Dictionary,Multi Index,我有一个区域类型的dict,在每个子区域的dict中,在每个数据帧对象的dict中,索引到我需要计算每个参数(列)时间序列的周期。此外,我需要它在两个单位 所以我创造了这样的东西: regions = ['region_x', 'region_y'] sub_regions = ['a', 'b', 'c'] parameters = ['x', 'y', 'z'] units = ['af', 'cbm'] start = datetime(2000, 01, 01) end = dateti
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
),并以某种方式将其插入到适当的位置。我已经成功地进入了单个嵌套dict并更新了数据帧对象(使用dict\ukey].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
它只是返回我刚开始的内容。如果您能就如何更新这些值提供任何建议,我将不胜感激。请原谅代码凌乱,这是我可以编写的最简单的代码来重现我(更难看)的问题。在
loc
试一试
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].loc[day, 'af'] = unit_af
tab_dict[region][sub_region][parameter].loc[day, 'cbm'] = unit_cbm