Skip to main content
 首页 » 编程设计

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

2024年12月31日21飞鱼

我有下面的 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)