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
它只是返回我開始的事情。我將不勝感激關於如何更新這些值的任何建議。請原諒那些亂七八糟的代碼,這是我寫的最簡單的代碼,可以重現我的(更醜陋的)問題。