使用Python将多个关系表转换为嵌套JSON格式 [英] Multiple relational tables to nested JSON format using Python

查看:608
本文介绍了使用Python将多个关系表转换为嵌套JSON格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用python/pandas组合多个关系表来创建嵌套的JSON对象.我是Python/pandas的初学者,所以在这里寻求帮助...

I'm trying to create nested JSON object by combining more than one relational tables using python/pandas. I'm a beginner in Python/pandas, so looking for bit of a help here...

在下面的示例中,为了保持简单起见,我使用的是CSV文件而不是表格

In the following example, instead of tables, I'm using CSV files just to keep it simple

Table1.csv

Emp_id,性别,年龄
1,M,32
2,M,35
3,F,31

Table1.csv

Emp_id, Gender, Age
1, M, 32
2, M, 35
3, F, 31

Emp_id,月,奖励
3000年8月1日
3500年9月1日
2000年10月1日
1500年8月2日,
5000年8月3日
2400年9月3日

Emp_id, Month, Incentive
1, Aug, 3000
1, Sep, 3500
1, Oct, 2000
2, Aug, 1500
3, Aug, 5000
3, Sep, 2400

我想创建一个如下所示的JSON对象

I want to create a JSON object like below

*必填输出:

{
    "data": [{
        "employee": 1,
        "gender": M,
        "age": 32,
        "incentive": [{
            "aug": 3000,
            "sep": 3500,
            "oct": 2000
        }],
        "employee": 2,
        "gender": M,
        "age": 35,
        "incentive": [{
            "aug": 1500
        }],
        "employee": 3,
        "gender": F,
        "age": 31,
        "incentive": [{
            "aug": 5000,
            "sep": 2400
        }]
    }]
}

推荐答案

使用 merge ,先左连接,然后 groupby ,带有针对字典的lambda函数,并转换

Use merge with left join first, then groupby with lambda function for dictionaries and convert to_dict, last add top key value and convert to json:

d = (df1.merge(df2, on='Emp_id', how='left')
         .groupby(['Emp_id','Gender','Age'])['Month','Incentive']
         .apply(lambda x: [dict(x.values)])
         .reset_index(name='Incentive')
         .to_dict(orient='records')

)
#print (d)

import json
json = json.dumps({'data':d})


print (json)

{
    "data": [{
        "Emp_id": 1,
        "Gender": "M",
        "Age": 32,
        "Incentive": [{
            "Aug": 3000,
            "Sep": 3500,
            "Oct": 2000
        }]
    }, {
        "Emp_id": 2,
        "Gender": "M",
        "Age": 35,
        "Incentive": [{
            "Aug": 1500
        }]
    }, {
        "Emp_id": 3,
        "Gender": "F",
        "Age": 31,
        "Incentive": [{
            "Aug": 5000,
            "Sep": 2400
        }]
    }]
}

这篇关于使用Python将多个关系表转换为嵌套JSON格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆