合并包含数据框的字典
Merge dictionary containing dataframes
我正在合并多个包含数据框作为值的字典。我将此作为参考(How to merge multiple dicts with same key or different key?)。但是合并字典中的值作为列表出现,我需要它是一个数据框。
df1 = pd.DataFrame([1,2,3])
df2 = pd.DataFrame([4,5,6])
df3 = pd.DataFrame([7,8,9])
d1 = {'a' : df1 , 'b' : df2}
d2 = {'c' : df3 , 'a' : df2}
dd = defaultdict(list)
for d in (d1, d2): # you can list as many input dicts as you want here
for key, value in d.items():
dd[key].append(value)
预期输出:
{'a' : df1 + df2 ,'b' : df2 , 'c': df3}
键不需要出现在所有字典中。使用 Python 3.
我认为这段代码正是您要找的:
df1 = pd.DataFrame([1,2,3])
df2 = pd.DataFrame([4,5,6])
df3 = pd.DataFrame([7,8,9])
d1 = {'a' : df1 , 'b' : df2}
d2 = {'c' : df3 , 'a' : df2}
dd = {}
for d in (d1, d2): # you can list as many input dicts as you want here
for key, value in d.items():
if key in dd.keys():
dd[key] += value
else:
dd[key] = value
我正在合并多个包含数据框作为值的字典。我将此作为参考(How to merge multiple dicts with same key or different key?)。但是合并字典中的值作为列表出现,我需要它是一个数据框。
df1 = pd.DataFrame([1,2,3])
df2 = pd.DataFrame([4,5,6])
df3 = pd.DataFrame([7,8,9])
d1 = {'a' : df1 , 'b' : df2}
d2 = {'c' : df3 , 'a' : df2}
dd = defaultdict(list)
for d in (d1, d2): # you can list as many input dicts as you want here
for key, value in d.items():
dd[key].append(value)
预期输出:
{'a' : df1 + df2 ,'b' : df2 , 'c': df3}
键不需要出现在所有字典中。使用 Python 3.
我认为这段代码正是您要找的:
df1 = pd.DataFrame([1,2,3])
df2 = pd.DataFrame([4,5,6])
df3 = pd.DataFrame([7,8,9])
d1 = {'a' : df1 , 'b' : df2}
d2 = {'c' : df3 , 'a' : df2}
dd = {}
for d in (d1, d2): # you can list as many input dicts as you want here
for key, value in d.items():
if key in dd.keys():
dd[key] += value
else:
dd[key] = value