pandas修改json数据结构

需求

{
    "sex": {
        "tome": "male",
        "jack": "female"
    },
    "age": {
        "tome": 18,
        "jack": 20
    }
}

转换成

{
    "tome":{
        "sex":"male",
        "age":18
    },
    "jack":{
        "sex":"female",
        "age":20
    }
}
import pandas as pd
import json

data = {
    "sex": {
        "tome": "male",
        "jack": "female"
    },
    "age": {
        "tome": 18,
        "jack": 20
    }
}
# 将原始数据转换为 Pandas DataFrame
df = pd.DataFrame(data)
# 使用 transpose() 方法转置 DataFrame
df_transposed = df.transpose()
print(df_transposed)
# 使用 to_dict() 方法转换为嵌套字典形式
output = df_transposed.to_dict()
# 使用 json.dumps() 方法将单引号替换为双引号
output_json = json.dumps(output)
print(output_json)

输出

     tome    jack
sex  male  female
age    18      20
{"tome": {"sex": "male", "age": 18}, "jack": {"sex": "female", "age": 20}}
posted @ 2024-01-12 10:59  朝阳1  阅读(12)  评论(0编辑  收藏  举报