需求
{
"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}}