Python dataframe到JSON添加其他字段
我希望将我的数据帧转换为jsonPython dataframe到JSON添加其他字段,python,json,pandas,Python,Json,Pandas,我希望将我的数据帧转换为json Age Eye Gender 30 blue male 在我当前的代码中,我将数据帧转换为json,并得到以下结果: json_file = df.to_json(orient='records') json_file [{'age':'30'},{'eye':'blue'},{'gender':'male'}] 但是,我想添加一个附加层,该层将为json数据声明id和名称,然后将其标记为“info” {'id':'5231'
Age Eye Gender
30 blue male
在我当前的代码中,我将数据帧转换为json,并得到以下结果:
json_file = df.to_json(orient='records')
json_file
[{'age':'30'},{'eye':'blue'},{'gender':'male'}]
但是,我想添加一个附加层,该层将为json数据声明id和名称,然后将其标记为“info”
{'id':'5231'
'name':'Bob'
'info': [
{'age':'30'},{'eye':'blue'},{'gender':'male'}
]
}
如何添加其他字段?我尝试阅读了,但是我没有看到关于如何在dataframe到json转换期间在中添加附加字段的明确答案。根据您提供的数据,这是您的答案:
import pandas as pd
a = {'id':'5231',
'name':'Bob',
}
df = pd.DataFrame({'Age':[30], 'Eye':['blue'], 'Gender': ['male']})
json = df.to_json(orient='records')
a['info'] = json
这些额外的信息来自哪里?它是什么格式的?嗨,如何将结果输出为json文件?@Hachi您可以使用此代码