将具有相同列/索引的两个pandas DataFrame连接到一个DataFrame中 [英] concat two pandas DataFrame with same column/index into one 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.Panel
与apply
+ 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屋!