Skip to main content
 首页 » 编程设计

python之在 JSON 序列化中嵌套一组带有新 header 的列

2024年12月31日8zhwl

我有一个这样的 Pandas 数据框

    start    end   compDepth compReleaseDepth compMeanRate 
0     0.0   0.62  58.0999985              1.5          110 
1    0.66   1.34  57.1399994                3           94 
2    1.42    2.1  57.1399994              2.5           89 
3    2.21   2.87  58.5699997              2.5           79 
4    2.97   3.65  55.2399979              3.5           77 
5    3.78   4.45  53.8600006              1.5           76 
6    4.49   5.17  62.2700005              0.5           81 
7    5.97   6.65  56.1899986              2.5           85 

我需要将数据序列化为 JSON,我使用了 df.to_json(orient='records') 并且工作正常。

但是,我想将最后 3 列嵌套到一个名为 "annotations" 的新标题中。这就是我想要实现的目标,有没有简单的方法可以做到这一点?

[{ 
        "start": "0.0", 
        "end": "0.62", 
        "annotations": { 
            "compDepth": "58.0999985", 
            "compReleaseDepth": "1.5", 
            "compMeanRate": "110" 
        } 
    }, { 
        "start": "0.66", 
        "end": "1.34", 
        "annotations": { 
            "compDepth": "57.1399994", 
            "compReleaseDepth": "3", 
            "compMeanRate": "94" 
        } 
    }, { 
        "start": "1.42", 
        "end": "2.1", 
        "annotations": { 
            "compDepth": "57.1399994", 
            "compReleaseDepth": "2.5", 
            "compMeanRate": "89" 
        } 
    }, { 
        "start": "2.21", 
        "end": "2.87", 
        "annotations": { 
            "compDepth": "58.5699997", 
            "compReleaseDepth": "2.5", 
            "compMeanRate": "79" 
        } 
    },  

请您参考如下方法:

一种简单的方法是使用 to_dict 将数据嵌套在新列中

df['annotations'] = df[['compDepth','compReleaseDepth','compMeanRate']].to_dict(orient='records') 

然后你只在最终输出中你想要的 3 列上使用 to_json(orient='records')

df[['start','end','annotations']].to_json(orient='records')