简体   繁体   English

结合字典的两个熊猫数据框

[英]Combine two pandas dataframes of dictionaries

I'd like to take 2 separate dataframes, each comprised of a bunch of dictionaries, and combine them to yield the following: 我想采用2个单独的数据帧,每个数据帧由一堆字典组成,并将它们组合以产生以下内容:

df1 = pd.DataFrame([[{'a':1}, {'a':2}]])
df2 = pd.DataFrame([[{'b':1}, {'b':2}]])
df3 = pd.some_function(df1, df2)

where pd.some_function takes the two dfs and performs a cell-wise merge of the dictionaries: 其中pd.some_function接受两个pd.some_function并执行字典的单元式合并:

                    0                   1
0  {u'a': 1, u'b': 1}  {u'a': 2, u'b': 2}

I know I can do this with a for loop, but is there a pandas function that can do this more succinctly? 我知道我可以使用for循环来做到这一点,但是有一个熊猫函数可以更简洁地做到这一点吗? Simply adding the dfs does not work. 仅仅添加dfs是行不通的。 I'm familiar with df.applymap , but my understanding is that will apply a function to each cell of a single df. 我熟悉df.applymap ,但是我的理解是,它将对单个df的每个单元格应用一个函数。

By using concat + ChainMap 通过使用concat + ChainMap

from collections import ChainMap


df=pd.concat([df1,df2])
df.groupby(df.index)[0,1].agg(lambda x :dict(ChainMap(*x.values.tolist())))
Out[94]: 
                  0                 1
0  {'b': 1, 'a': 1}  {'b': 2, 'a': 2}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM