【问题标题】:Converting JSON to Pandas dataframe, allowing for complex dict structures将 JSON 转换为 Pandas 数据帧,允许复杂的 dict 结构
【发布时间】:2021-12-18 14:17:00
【问题描述】:

以下是我的代码,其中出现错误“将字典与非系列混合可能会导致排序不明确”。是什么原因,我应该如何解决这个问题?如何在 python 中可视化这个字典以便调试?

import pandas as pd
df = pd.read_json('https://stats.oecd.org/sdmx-json/data/QNA/AUS+AUT.GDP+B1_GE.CUR+VOBARSA.Q/all?startTime=2009-Q2&endTime=2011-Q4')

提前致谢。

【问题讨论】:

  • 谢谢大家。我找到了一个简单的解决方案,只需这样做: df = pd.read_csv(url + r'&contentType=csv')

标签: json pandas dataframe


【解决方案1】:

下载json文件并执行:

from pandas.io.json import json_normalize
import json

with open('aaa.json') as data_file:    
    d= json.load(data_file)

df = json_normalize(d)

给出:

             dataSets  \
0  [{'action': 'Information', 'series': {'0:0:0:0...   

                              header.id  header.test  \
0  a0d6c1d0-79b9-4cc2-9e7a-06050c934194        False   

                header.prepared header.sender.id  \
0  2021-11-04T10:42:25.7631355Z             OCDE   

                                  header.sender.name  \
0  Organisation de coopération et de développem...   

                                        header.links  \
0  [{'href': 'https://stats.oecd.org:443/sdmx-jso...   

                                     structure.links  \
0  [{'href': 'https://stats.oecd.org/sdmx-json/da...   

                   structure.name           structure.description  \
0  Comptes nationaux trimestriels  Comptes nationaux trimestriels   

                         structure.dimensions.series  \
0  [{'keyPosition': 0, 'id': 'LOCATION', 'name': ...   

                    structure.dimensions.observation  \
0  [{'id': 'TIME_PERIOD', 'name': 'Période', 'va...   

  structure.attributes.dataSet  \
0                           []   

                         structure.attributes.series  \
0  [{'id': 'TIME_FORMAT', 'name': 'Time Format', ...   

                    structure.attributes.observation  \
0  [{'id': 'OBS_STATUS', 'name': 'Observation Sta...   

                               structure.annotations  
0  [{'title': 'Copyright OECD - All rights reserv...  

请注意,您有嵌套的 json,您必须取消嵌套。例如使用:

def flatten_nested_json_df(df):
    df = df.reset_index()
    s = (df.applymap(type) == list).all()
    list_columns = s[s].index.tolist()
    
    s = (df.applymap(type) == dict).all()
    dict_columns = s[s].index.tolist()

    
    while len(list_columns) > 0 or len(dict_columns) > 0:
        new_columns = []

        for col in dict_columns:
            horiz_exploded = pd.json_normalize(df[col]).add_prefix(f'{col}.')
            horiz_exploded.index = df.index
            df = pd.concat([df, horiz_exploded], axis=1).drop(columns=[col])
            new_columns.extend(horiz_exploded.columns) # inplace

        for col in list_columns:
            print(f"exploding: {col}")
            df = df.drop(columns=[col]).join(df[col].explode().to_frame())
            new_columns.append(col)

        s = (df[new_columns].applymap(type) == list).all()
        list_columns = s[s].index.tolist()

        s = (df[new_columns].applymap(type) == dict).all()
        dict_columns = s[s].index.tolist()
    return df

【讨论】:

    【解决方案2】:

    你可以使用 Dframcy。

    from dframcy import DframCy
    
    with open('aaa.json') as data_file:    
        d= json.load(data_file)
    
    dataframe = dframcy.to_dataframe(d, columns=["text","start","","","","",""])
    

    【讨论】:

      猜你喜欢
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 2021-05-02
      • 2013-05-15
      • 2019-12-20
      • 1970-01-01
      • 2018-12-31
      相关资源
      最近更新 更多