如何将多个列转换为JSON并按Python中的另一列对它们进行分组

如何将多个列转换为JSON并按Python中的另一列对它们进行分组,python,json,pandas,Python,Json,Pandas,问题已被删除,信息已被删除。假设您拥有以下结构的数据帧: import pandas as pd import json df = pd.DataFrame({ 'order_number': [1,2,3,4,5], 'line_item_id': ['a', 'b', 'c', 'd', 'e'], 'reason': ['r1', 'r2', 'r3', 'r4', 'r5'], 'quantity': [100, 200, 300, 400, 500],

问题已被删除,信息已被删除。

假设您拥有以下结构的数据帧:

import pandas as pd
import json

df = pd.DataFrame({
    'order_number': [1,2,3,4,5],
    'line_item_id': ['a', 'b', 'c', 'd', 'e'],
    'reason': ['r1', 'r2', 'r3', 'r4', 'r5'],
    'quantity': [100, 200, 300, 400, 500],
    'status': ['ok', 'ok', 'error', 'ok', 'ok']
                   
})

df.head()
输出:

{
    "1": {
        "line_item_id": "a",
        "reason": "r1",
        "quantity": "100",
        "status": "ok"
    },
    "2": {
        "line_item_id": "b",
        "reason": "r2",
        "quantity": "200",
        "status": "ok"
    },
    "3": {
        "line_item_id": "c",
        "reason": "r3",
        "quantity": "300",
        "status": "error"
    },
    "4": {
        "line_item_id": "d",
        "reason": "r4",
        "quantity": "400",
        "status": "ok"
    },
    "5": {
        "line_item_id": "e",
        "reason": "r5",
        "quantity": "500",
        "status": "ok"
    }
}

将dataframe解析为json:

d = { f"{df.loc[i]['order_number']}" : {
    'line_item_id' : df.loc[i]['line_item_id'],
    'reason' : df.loc[i]['reason'],
    'quantity' : str(df.loc[i]['quantity']),
    'status' : df.loc[i]['status']
    } for i in df.index }

result = json.dumps(d)

print(result)
解析时,您可能会遇到诸如“int64类型的对象不可JSON序列化”之类的异常,这意味着某些列需要转换为int或string。在本例中,“数量”列被转换为字符串

输出:

{
    "1": {
        "line_item_id": "a",
        "reason": "r1",
        "quantity": "100",
        "status": "ok"
    },
    "2": {
        "line_item_id": "b",
        "reason": "r2",
        "quantity": "200",
        "status": "ok"
    },
    "3": {
        "line_item_id": "c",
        "reason": "r3",
        "quantity": "300",
        "status": "error"
    },
    "4": {
        "line_item_id": "d",
        "reason": "r4",
        "quantity": "400",
        "status": "ok"
    },
    "5": {
        "line_item_id": "e",
        "reason": "r5",
        "quantity": "500",
        "status": "ok"
    }
}

请出示您的数据样本。@Manakin请查看文章底部的链接,感谢您回复methis。这不是一个请阅读并格式化您的问题。我已对其进行了排序。谢谢,但生成一个空数据框并将虚拟数据传递给它并不难。我只想知道如何将b、c、d、e列合并成json格式,并按a列进行分组。您可以将任何需要的数据放入列中。如果您无法做到这一点,那么可能这个问题不适合您。因此,请始终提供一个包含代码、数据、错误、当前输出和预期输出的文本。只有绘图图像是可以的。请看。否则,你的问题很可能会被否决和关闭。如果你的问题以这种方式结束,那么在一段时间内你将被禁止提问。