【问题标题】:Python pandas extract data from nested listPython pandas 从嵌套列表中提取数据
【发布时间】:2022-01-05 20:23:35
【问题描述】:

对于个人项目,我从 Google Books API 调用数据并将我想要的字段上传到 mySQL。

我已成功发出 API 请求并收到数据。收到的数据是嵌套的,我想把它放在一个数据框中。现在我的代码适用于“第一”列(无缩进)。之后的所有数据,我无法在数据框中输入。

一小部分 API 输出:

    {
  "kind": "books#volumes",
  "totalItems": 1,
  "items": [
    {
      "kind": "books#volume",
      "id": "vH_vwQEACAAJ",
      "etag": "Gzpw8EnKpVY",
      "selfLink": "https://www.googleapis.com/books/v1/volumes/vH_vwQEACAAJ",
      "volumeInfo": {
        "title": "Crash course programmeren in Python",
        "subtitle": "projectgericht leren programmeren",

下面是我的python代码:

import requests
import pandas as pd
import json

request_string = "https://www.googleapis.com/books/v1/volumes?q=isbn:9789059056749&key=###KEY###"
response = requests.get(request_string).text
response_json = json.loads(response)
response_json_normalized = pd.json_normalize(response_json)

author_df = pd.DataFrame(data=response_json_normalized, columns=['title'])
print(author_df)

当使用 columns=['totalItems'] 时,值 1 在 Dataframe 中,但当使用 columns=['title'] 时,它显示 NaN。例如,id 也是如此。

我错过了一些简单的东西吗?还是我的方法不对?

我们的目标是最终将数据输入到 mySQL 数据库中,以便对我拥有的所有书籍进行分类。感谢您对未来步骤的任何建议!

【问题讨论】:

  • pd.json_normalize(response_json, "items") 可能会给你你想要的......你可以通过'volumnInfo.title'访问标题列

标签: python json pandas dataframe


【解决方案1】:

这对我有用。

import requests
import pandas as pd
import json
from pandas import json_normalize

request_string = "https://www.googleapis.com/books/v1/volumes?q=isbn:9789059056749&key=###KEY###"
response = requests.get(request_string).text
response_json = json.loads(response)
recs = response_json['items']
df = json_normalize(recs)



    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    相关资源
    最近更新 更多