【问题标题】:How to convert pandas DataFrame to json for django model?如何将 pandas DataFrame 转换为 json 用于 django 模型?
【发布时间】:2018-12-10 00:38:46
【问题描述】:

我有下面的 Pandas DataFrame,需要将其转换为 json 格式,其中 df.columns 包含在 Django 模型名称和“fields”字段名称中。请参阅下面的示例,了解 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",
    }
  }
]

【问题讨论】:

标签: python json django pandas


【解决方案1】:

我们可以将数据框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)

【讨论】:

    猜你喜欢
    • 2017-04-13
    • 2021-03-29
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 2019-06-09
    • 2017-01-08
    • 2023-03-31
    相关资源
    最近更新 更多