合并字典列表

时间:2019-02-21 22:47:02

标签: python pandas dictionary

下面是包含字典的列表,这些字典本身包含要合并的数据框。

ls = [{'varID': 101, 'varDesc': 'Description of variable 101', 'values': df101},
      {'varID': 102, 'varDesc': 'Description of variable 102', 'values': df102},
      {'varID': 103, 'varDesc': 'Description of variable 103', 'values': df103}]

其中df101,df102和df103均为 x ,其形状为1个数据框,且日期值作为索引(名为“ refPer”),所有数据框中的“值”列名称。 注意:对于所有日期框架, x 的大小都不相同。

我想合并数据框并尝试以下操作:

mergedDF = reduce(lambda x,y: pd.merge(x.get('values'),y.get('values'), how = 'outer', on = 'refPer'), ls)

但是,出现以下错误:

ValueError: can not merge DataFrame with instance of type <class 'NoneType'>

任何帮助将不胜感激。

提前谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用concat来连接长度不等的数据帧。您还可以提供参数keys,以为要连接的每个数据框命名。您将创建一个多索引,但是如果您不想要它,可以将其删除:

df = pd.concat([x['values'] for x in ls], axis=1, keys=[x['varID'] for x in ls])
df.columns = df.columns.droplevel(1)  # removes 'original' level
相关问题