我正在尝试将多个 pandas.DataFrame
合并到一个集合中的 MongoDB 中,所有数据帧都具有相同的索引/列,我想将其保存在一个集合中文档,使用 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
和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
的列实际上是索引。否则,请确保它们是:
df1 = df1.set_index('index')
df2 = df2.set_index('index')
关于json - 将两个具有相同列/索引的 pandas DataFrame 连接到一个 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43264668/