简体   繁体   English

Python - 数据框合并 + JSON

[英]Python - Dataframe Merge + JSON

| |id|a|b
|1| 5|1|4
|2|10|2|5
|3|15|3|6
     +
| |id|a |b
|1| 5|10|13
|2|10|11|14
|3|15|12|15
     =
| |id|  a  |  b
|1| 5|1, 10|4, 13
|2|10|2, 11|5, 14
|3|15|3, 12|6, 15

I am trying to merge two dataframes by id and save the result in json file.我正在尝试通过 id 合并两个数据帧并将结果保存在 json 文件中。

Using pd.concat and df.groupby and df.agg使用pd.concatdf.groupbydf.agg

df3 = pd.concat([df1, df2]).groupby('id', as_index=False).agg({'a': lambda x: ', '.join(map(str, x)), 'b': lambda x: ', '.join(map(str, x))})
print(df3)

Output:输出:

   id      a      b
0   5  1, 10  4, 13
1  10  2, 11  5, 14
2  15  3, 12  6, 15

you can use df.to_json() to convert to json您可以使用df.to_json()转换为 json

print(df3.to_json())

Output:输出:

{
  "id": {
    "0": 5,
    "1": 10,
    "2": 15
  },
  "a": {
    "0": "1, 10",
    "1": "2, 11",
    "2": "3, 12"
  },
  "b": {
    "0": "4, 13",
    "1": "5, 14",
    "2": "6, 15"
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM