【问题标题】:How to convert this json file to pandas dataframe如何将此 json 文件转换为 pandas 数据框
【发布时间】:2019-04-15 17:41:40
【问题描述】:

文件中的格式是这样的

{ 'match' : 'a', 'score' : '2'},{......}

我已经尝试过 pd.DataFrame 并且我也尝试过逐行阅读它,但它在一个单元格中为我提供了所有内容

我是 python 新手

提前致谢

预期结果是一个熊猫数据框

【问题讨论】:

  • 列总是匹配的吗? IE。 JSON 文件是 {'match': 'a', 'score': '2'}, {'match':'b', 'score':'3'}?还是字典有不同的键值对?
  • 请不要忘记accept答案之一,@bsa1player。

标签: json python-3.x pandas


【解决方案1】:

尝试使用json_normalize()函数

例子:

from pandas.io.json import json_normalize

values = [{'match': 'a', 'score': '2'}, {'match': 'b', 'score': '3'}, {'match': 'c', 'score': '4'}]
df = json_normalize(values)
print(df)

输出:

【讨论】:

    【解决方案2】:

    如果您的文件的一行对应一个 JSON 对象,您可以执行以下操作:

    # import library for working with JSON and pandas
    import json 
    import pandas as pd
    
    # make an empty list
    data = []
    
    # open your file and add every row as a dict to the list with data
    with open("/path/to/your/file", "r") as file:
        for line in file:
            data.append(json.loads(line))
    
    # make a pandas data frame
    df = pd.DataFrame(data)
    

    如果文件的一行中只有一个以上的 JSON 对象,那么您应该找到这些 JSON 对象,例如 here 是两个可能的选项。第二个选项的解决方案如下所示:

    # import all you will need
    import pandas as pd
    import json
    from json import JSONDecoder
    
    # define function
    def extract_json_objects(text, decoder=JSONDecoder()):
        pos = 0
        while True:
            match = text.find('{', pos)
            if match == -1:
                break
            try:
                result, index = decoder.raw_decode(text[match:])
                yield result
                pos = match + index
            except ValueError:
                pos = match + 1
    
    # make an empty list
    data = []
    
    # open your file and add every JSON object as a dict to the list with data
    with open("/path/to/your/file", "r") as file:
        for line in file:
            for item in extract_json_objects(line):
                data.append(item)
    
    # make a pandas data frame
    df = pd.DataFrame(data)
    

    【讨论】:

      猜你喜欢
      • 2014-04-15
      • 2020-02-29
      • 2020-10-31
      • 2020-10-31
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多