【问题标题】:Convert Pandas Dataframe to JSON format: how to group将 Pandas Dataframe 转换为 JSON 格式:如何分组
【发布时间】:2021-02-24 00:26:55
【问题描述】:

我有一个 Pandas 数据框:

     nodes        x      y        z
0        1   0.0000  0.000   0.0000
1        2   0.0000  9.144   0.0000
2        3  19.5072  0.000   0.0000
3        4  19.5072  9.144   0.0000
4        5   9.7536  0.000   0.0000
..     ...      ...    ...      ...
175    176  19.5072  9.144  27.7368
176    177  19.5072  9.144  25.7556
177    178  19.5072  9.144  21.7932
178    179  19.5072  9.144  19.8120
179    180  19.5072  9.144  17.8308

转换为 JSON:

{
    "nodes": {
        "1": {
            "x": 0,
            "y": 0,
            "z": 0
        },
        "2": {
            "x": 0,
            "y": 9.144,
            "z": 0
        },
        "3": {
            "x": 19.5072,
            "y": 0,
            "z": 0
        },
        "4": {
            "x": 19.5072,
            "y": 9.144,
            "z": 0
        },
        "5": {
            "x": 9.7536,
            "y": 0,
            "z": 0
        },
    },
}

我刚开始使用python。谷歌之后,我尝试了:

out = df.to_json(orient = 'records')
print(json.dumps(json.loads(out), indent=4))

结果:

{
    "nodes": 1,
    "x": 0.0,
    "y": 0.0,
    "z": 0.0
},
{
    "nodes": 2,
    "x": 0.0,
    "y": 9.144,
    "z": 0.0
},
{
    "nodes": 3,
    "x": 19.5072,
    "y": 0.0,
    "z": 0.0
},

请帮忙。谢谢。

【问题讨论】:

    标签: python json pandas dataframe


    【解决方案1】:

    您可以利用groupby 函数来实现您想要的输出:

    out = {'nodes': df.groupby('nodes').last().to_dict(orient='index')}
    print(json.dumps(out, indent=4))
    

    结果:

    {
        "nodes": {
            "1": {
                "x": 0.0,
                "y": 0.0,
                "z": 0.0
            },
            "2": {
                "x": 0.0,
                "y": 9.144,
                "z": 0.0
            },
            "3": {
                "x": 19.5072,
                "y": 0.0,
                "z": 0.0
            },
            "4": {
                "x": 19.5072,
                "y": 9.144,
                "z": 0.0
            },
            "5": {
                "x": 9.7536,
                "y": 0.0,
                "z": 0.0
            }
        }
    }
    

    【讨论】:

    • @drec4s。有用。谢谢你。你能告诉函数.last()吗?
    • out = {'nodes': df.groupby('nodes').last().to_dict(orient='index')} 工作;否则,您将收到警告FutureWarning: Indexing with multiple keys (implicitly converted to a tuple of keys) will be deprecated, use a list instead.
    猜你喜欢
    • 2017-01-08
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2017-04-13
    • 2021-03-29
    • 1970-01-01
    相关资源
    最近更新 更多