【问题标题】:Load json file with string into pandas dataframe in python将带有字符串的json文件加载到python中的pandas数据框中
【发布时间】:2021-08-16 00:57:44
【问题描述】:

我有一个示例 json 数据集:

['[{"id":"123","product":"dell","date":"2019-01-01","sales":5,"created_at":"2019-01-26 15:00:00"}, {"id":"124","product":"apple","date":"2019-01-02","sales":7,"created_at":"2019-01-27 15:00:00"}]']

我想从这个 json 数据创建一个 pandas 数据框,但是当我使用 json_normalize 方法时,我得到 AttributeError: 'str' object has no attribute 'values'。

预期的输出应该是这样的:

id   product  date        sales   created_at
123.  dell.   2019-01-01.  5.     2019-01-26 15:00:00
124.  apple.  2019-01-02.  7.     2019-01-27 15:00:00

【问题讨论】:

  • pd.read_json(yourlist[0]) ?如果那是一个列表
  • "... 一个示例 json 数据集作为..." - 好吧,您是如何获得该数据集的?也许您只是错误地加载了它?
  • 我尝试了 list[0] 但由于结果是类型字符串而不起作用。
  • 使用 json.loads 将您的字符串转换为 python 对象,然后将其加载到 df stackoverflow.com/a/4917044/5125264
  • 我试过了,那是当我得到一个字符串列表的输出时。

标签: python pandas numpy data-science


【解决方案1】:

当我得到一个字符串列表的输出时

如果 json.load... 的结果是这样的

a = ['[{"id":"123","product":"dell","date":"2019-01-01","sales":5,"created_at":"2019-01-26 15:00:00"}, {"id":"124","product":"apple","date":"2019-01-02","sales":7,"created_at":"2019-01-27 15:00:00"}]']

然后再做一次......

>>> b = json.loads(a[0])
>>> b
[{'id': '123', 'product': 'dell', 'date': '2019-01-01', 'sales': 5, 'created_at': '2019-01-26 15:00:00'}, {'id': '124', 'product': 'apple', 'date': '2019-01-02', 'sales': 7, 'created_at': '2019-01-27 15:00:00'}]
>>> pd.DataFrame(b)
    id product        date  sales           created_at
0  123    dell  2019-01-01      5  2019-01-26 15:00:00
1  124   apple  2019-01-02      7  2019-01-27 15:00:00
>>>

不幸的是,您无法提前知道自己需要这样做。您需要先检查数据。除非你有幸拥有制作这些 json 的 事物 的规范。

【讨论】:

    【解决方案2】:
    import json
    import pandas as pd
    x = ['[{"id":"123","product":"dell","date":"2019-01-01","sales":5,"created_at":"2019-01-26 15:00:00"}, {"id":"124","product":"apple","date":"2019-01-02","sales":7,"created_at":"2019-01-27 15:00:00"}]']
    # Take 0th element of list
    x = x[0]
    info = json.loads(x)
    df = pd.json_normalize(info)
    df
    

    这是我测试的代码,它对我有用。

    如果有帮助,请接受这个答案。

    【讨论】:

      猜你喜欢
      • 2021-08-06
      • 2016-06-08
      • 1970-01-01
      • 2019-12-28
      • 2017-06-03
      • 2017-11-15
      • 2016-09-19
      • 2021-04-22
      • 2021-10-04
      相关资源
      最近更新 更多