将具有相同列/索引的两个pandas DataFrame连接到一个DataFrame中 [英] concat two pandas DataFrame with same column/index into one DataFrame

查看:458
本文介绍了将具有相同列/索引的两个pandas DataFrame连接到一个DataFrame中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将多个pandas.DataFrame合并以保存在mongodb中的一个集合中,所有数据框都具有相同的索引/列,我想使用方法.将数据帧的所有单元格作为字典,这可能是一个很好的方法.为此,我想像这样连接数据框:

I'm trying to concat multiples pandas.DataFrame to be saved in a mongodb in just one collection, all the dataframes have the same index/columns and I wanted to save it, in just one document, using to_json() method. Having all the cells of the dataframe as dicts, its probably a good approach. To accomplish that I wanted to concat the dataframes like this:

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'}

有没有一种方法可以在不使用迭代器的情况下实现?任何指导将不胜感激!谢谢!

is there a way to accomplish that without using an iterator?, any guidance will be appreciate!. Thanks!

推荐答案

pd.Panelapply + pd.Series.to_dict

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'}


这是假设您标记为index的列实际上是索引.否则,请确保它们是


This is assuming the columns you have labeled index are in fact the index. Otherwise, make sure they are:

df1 = df1.set_index('index')
df2 = df2.set_index('index')

这篇关于将具有相同列/索引的两个pandas DataFrame连接到一个DataFrame中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆