将Hierarchyl JSON文件导入datafram

2024-09-30 10:32:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在寻找解决我问题的办法,但找不到任何适用的办法。我正在尝试将一个高维JSON文件导入到一个数据帧中。你知道吗

结构类似于:

{   'manufacturing_plant_events':
        {   'data':
            {   'shiftInformation':
                {   'shift1':
                    { 'color': 'red'
                        , 'amount' : 32
                        , 'order' : None
                    },
                    'shift2':
                    { 'color': 'blue'
                        , 'amount' : 44
                        , 'order' : 1
                    },
                    'shift3':
                    { 'color': 'green'
                        , 'amount' : 98
                        , 'order' : 2
                    }
                }
            ...}
        ...}
    }

我尝试过许多解决方案,包括:

  • 你知道吗json.loads文件()
  • 你知道吗pd.数据帧(json)
  • json\u规范化(json)
  • 你知道吗pd.read\u json文件(json)

还有一些人,我试着把我的数组展平,然后把它转换成一个数据帧bu,但也不起作用。我不确定这是否可行,或者dataframe是否只支持几个级别的嵌套。你知道吗

我尝试过的扁平化只是尝试在包含叶信息的数据帧中创建列。因此,我也可以使用dataframe,它具有以下列名完整路径和值,即存储在节点中的实际值。你知道吗

数据帧中的第一行:

(
manufacturing_plant_events.data.shiftInformation.shift1.color
'red'

manufacturing_plant_events.data.shiftInformation.shift1.amount
32

manufacturing_plant_events.data.shiftInformation.shift1.order
None
)

等等。你知道吗

任何关于如何解决这一问题的建议都将受到高度赞赏。你知道吗


Tags: 文件数据nonejsondataorderredevents
1条回答
网友
1楼 · 发布于 2024-09-30 10:32:55

我将dict展平,得到了一个数据帧:

import pandas as pd

def flat_dict(dictionary, prefix):
    if type(dictionary) == dict:
        rows = []

        for key, items in dictionary.items():
            rows += flat_dict(items, prefix + [key])   

        return rows

    else:
        return [prefix + [dictionary]]

def dict_to_df(dictionary):        
    return pd.DataFrame(flat_dict(dictionary, []))

当然,您需要首先通过json包将json作为dict导入。你知道吗

相关问题 更多 >

    热门问题