python - 如何将两个 JSON 文件与 pandas 合并

标签 python json pandas

我正在尝试做一个合并 2 个 json 文件的 python 脚本,例如:

第一个文件:students.json

{"John Smith":{"age":16, "id": 1}, ...., "Paul abercom":{"age":18, "id": 764}}

第二个文件:teacher.json

{"Agathe Magesti":{"age":36, "id": 765}, ...., "Tom Ranliver":{"age":54, "id": 801}}

所以在第一时间,为了不丢失任何信息,我修改了文件以添加每个人的状态:

{"John Smith":{"age":16, "id": 1, "status":"student"}, ...., "Paul abercom":{"age":18, "id": 764, "status":"student"}}

{"Agathe Magesti":{"age":36, "id": 765, "status":"teacher"}, ...., "Tom Ranliver":{"age":54, "id": 801, "status":"teacher"}}

为此,我编写了以下代码:

import pandas as pd
type_student = pd.read_json('student.json')
type_student.loc["status"] = "student"
type_student.to_json("testStudent.json")
type_teacher = pd.read_json('teacher.json')
type_teacher.loc["status"] = "teacher"
type_teacher.to_json("testTeacher.json")
with open("testStudent.json") as data_file:
   data_student = json.load(data_file)
with open("testTeacher.json") as data_file:
   data_teacher = json.load(data_file)

我想做的是合并 data_student 和 data_teacher 并将生成的 JSON 打印到 json 文件中,但我只能使用标准库、pandas、numpy 和 scipy。

经过一些测试,我意识到有些老师也是学生,这可能是合并的问题。

最佳答案

您的 JSON 文件似乎包含“对象”作为顶级结构。这些映射到 Python 字典。所以这应该很容易使用 Python。只需用第二个字典更新第一个字典即可。

import json

with open("mel1.json") as fo:
    data1 = json.load(fo)

with open("mel2.json") as fo:
    data2 = json.load(fo)

data1.update(data2)

with open("melout.json", "w") as fo:
    json.dump(data1, fo)

关于python - 如何将两个 JSON 文件与 pandas 合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35235778/

相关文章:

python - django 信号是否也包含在 transaction.atomic 装饰器中?

ios - 如何在 UITableviewcells 中显示 HTML 颜色代码

python - 在我的 Matplotlib 中不显示时间,只显示日期

python - 如何按年份过滤 sqlalchemy 中的查询(日期时间列)

python - 通过python执行带空格的sudo命令

android - 如何使用毕加索在android中显示水平 ScrollView 中的图像作为幻灯片 View

python - 具体异常输出

python - geopandas 的最快方法(读取和空间连接)

python pandas滚动窗口并重新创建数据框

python - 计算 python 中重叠滑动窗口中的值