gpt4 book ai didi

python - 如何将 pandas DataFrame 转换为 json 用于 django 模型?

转载 作者:太空宇宙 更新时间:2023-11-04 04:38:38 25 4
gpt4 key购买 nike

我有下面的 Pandas DataFrame,需要将其转换为 json 格式,并将 df.columns 包裹在 Django 模型名称和“字段”字段名称中。请参阅下面的 json 外观示例。我应该怎么做?

df:

+-----------------+---------+------+
| Artist | Title | Year |
+-----------------+---------+------+
| Michael Jackson | Beat it | 1988 |
| Britney Spears | Lucky | 2012 |
| Justin Bieber | Baby | 2006 |
+-----------------+---------+------+

Json文件输出:

[
{
"model": "profiles.track",
"fields": {
"artist": "Michael Jackson",
"title": "Beat it",
"year": "1988",
}
},
{
"model": "profiles.track",
"fields": {
"artist": "Britney Spears",
"title": "Lucky",
"year": "2012",
}
},
{
"model": "profiles.track",
"fields": {
"artist": "Justin Bieber",
"title": "Baby",
"year": "2006",
}
}
]

最佳答案

我们可以将数据框 df 转换为字典列表:

df_dicts = df.T.to_dict().values()

当然,这并没有给我们完整的请求格式,这也不是一个 JSON blob。但是我们可以以此为基础来扩展它。例如,我们可以通过执行 mapping 将每个字典包装到另一个字典中:

result = list(map(lambda x: {'model': 'profiles.track', 'fields': x}, df_dicts))

最后我们可以构造一个 JSON blob:

import json

json_blob = json.dumps(result)

这将构建一个字符串,它是 result 的 JSON 转储。例如,我们可以打印它:

print(json_blob)

关于python - 如何将 pandas DataFrame 转换为 json 用于 django 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51125082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com