将两个 pandas 数据帧合并为一个数据帧 "dict type cell"(pd.Panel 已弃用)

combine two pandas dataframe into one dataframe "dict type cell" (pd.Panel deprecated)

我正在尝试连接多个 pandas.DataFrame 以保存在一个集合中的 mongodb 中,所有数据帧都具有相同的 index/columns 我想保存它,在一个文档中,使用 to_json() 方法。将数据框的所有单元格作为字典,这可能是一个好方法。为此,我想像这样连接数据帧:

df1:                
 index   A      B
 1     'A1'   'B1'
 2     'A2'   'B2'
 3     'A3'   'B3'

df2:
 index  A      B
 1    'a1'   'b1'
 2    'a2'   'b2'
 3    'a3'   'b3'

预期解决方案:

df_sol:
 index    A                    B
 1        {d1:'A1', d2:'a1'}   {d1:'B1', d2:'b1'}
 2        {d1:'A2', d2:'a2'}   {d1:'B2', d2:'b2'}
 3        {d1:'A3', d2:'a3'}   {d1:'B3', d2:'b3'}

我使用的方法是

pd.Panel(dict(d1=df1, d2=df2)).apply(pd.Series.to_dict, 0)

                              A                         B
index                                                    
1      {'d1': 'A1', 'd2': 'a1'}  {'d1': 'B1', 'd2': 'b1'}
2      {'d1': 'A2', 'd2': 'a2'}  {'d1': 'B2', 'd2': 'b2'}
3      {'d1': 'A3', 'd2': 'a3'}  {'d1': 'B3', 'd2': 'b3'}

但是 pd.Panel 它已被弃用 DeprecationWarning : Panel is deprecated and will be removed in a future version. 它有一个仅使用 pandas 的解决方法吗? 谢谢!

解决方案
pd.concat + 其他内容

pd.Series(
    pd.concat([df1, df2], axis=1, keys=['d1', 'd2']).stack().to_dict('index')
).unstack()

                              A                             B
1  {'d1': ''A1'', 'd2': ''a1''}  {'d1': ''B1'', 'd2': ''b1''}
2  {'d1': ''A2'', 'd2': ''a2''}  {'d1': ''B2'', 'd2': ''b2''}
3  {'d1': ''A3'', 'd2': ''a3''}  {'d1': ''B3'', 'd2': ''b3''}

说明
我想将 [1, 2, 3]['A', 'B'] 放入索引并将 ['d1', 'd2'] 作为列。

我从 pd.concat

开始
pd.concat([df1, df2], axis=1, keys=['d1', 'd2'])

         d1          d2      
          A     B     A     B
index                        
1      'A1'  'B1'  'a1'  'b1'
2      'A2'  'B2'  'a2'  'b2'
3      'A3'  'B3'  'a3'  'b3'

这几乎让我到达那里。如果我在后面加上 stack,它会将列的最后一级放入索引的最后一级:

pd.concat([df1, df2], axis=1, keys=['d1', 'd2']).stack()

           d1    d2
index              
1     A  'A1'  'a1'
      B  'B1'  'b1'
2     A  'A2'  'a2'
      B  'B2'  'b2'
3     A  'A3'  'a3'
      B  'B3'  'b3'

这就是我想要的。从这里我可以使用 .to_dict('index')

pd.concat([df1, df2], axis=1, keys=['d1', 'd2']).stack().to_dict('index')

{(1, 'A'): {'d1': "'A1'", 'd2': "'a1'"},
 (1, 'B'): {'d1': "'B1'", 'd2': "'b1'"},
 (2, 'A'): {'d1': "'A2'", 'd2': "'a2'"},
 (2, 'B'): {'d1': "'B2'", 'd2': "'b2'"},
 (3, 'A'): {'d1': "'A3'", 'd2': "'a3'"},
 (3, 'B'): {'d1': "'B3'", 'd2': "'b3'"}}

并将其传递回 pd.Series 构造函数以获取一系列字典。

pd.Series(
    pd.concat([df1, df2], axis=1, keys=['d1', 'd2']).stack().to_dict('index')
)

1  A    {'d1': ''A1'', 'd2': ''a1''}
   B    {'d1': ''B1'', 'd2': ''b1''}
2  A    {'d1': ''A2'', 'd2': ''a2''}
   B    {'d1': ''B2'', 'd2': ''b2''}
3  A    {'d1': ''A3'', 'd2': ''a3''}
   B    {'d1': ''B3'', 'd2': ''b3''}
dtype: object

唯一剩下要做的就是unstack,我在上面的解决方案中展示了它。

这是一个完全不同的概念,我很喜欢。


您可以创建 dict 的子类,我们将加法定义为字典合并。

from cytoolz.dicttoolz import merge

class mdict(dict):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def __add__(self, other):
        return(mdict(merge(self, other)))


df1.applymap(lambda x: mdict(d1=x)) + df2.applymap(lambda x: mdict(d2=x))

                                  A                             B
index                                                            
1      {'d1': ''A1'', 'd2': ''a1''}  {'d1': ''B1'', 'd2': ''b1''}
2      {'d1': ''A2'', 'd2': ''a2''}  {'d1': ''B2'', 'd2': ''b2''}
3      {'d1': ''A3'', 'd2': ''a3''}  {'d1': ''B3'', 'd2': ''b3''}