json - 将两个具有相同列/索引的 pandas DataFrame 连接到一个 DataFrame

标签 json mongodb pandas

我正在尝试将多个 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.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的列实际上是索引。否则,请确保它们是:

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

关于json - 将两个具有相同列/索引的 pandas DataFrame 连接到一个 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43264668/

相关文章:

java.lang.IllegalArgumentException : No more parsing elements

mysql - 投票系统的数据库设计

javascript - 通过 React 从 mongoDB 中检索数据

python - 如何使用来自多列的参数调用 pandas.rolling.apply?

python - 在 python Pandas 中绘制来自更多不同数据帧的堆积条

python - 有效地获得 3 个不同大小和类型的 numpy 数组的排列

C# 列表序列化 json 字符串

angularjs - 使用 .json 文件或数据库来存储静态数据?

json - Java EE7 REST 服务器不再将 List<String> 作为 JSON 返回

c# - 如何在 C# 中获取 MongoDbRef