Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将Hierarchical JSON文件导入数据帧_Python_Json_Pandas - Fatal编程技术网

Python 将Hierarchical JSON文件导入数据帧

Python 将Hierarchical JSON文件导入数据帧,python,json,pandas,Python,Json,Pandas,我一直在寻找解决问题的方法,但找不到任何适用的方法。我正在尝试将一个高维JSON文件导入到一个数据帧中 结构类似于: { 'manufacturing_plant_events': { 'data': { 'shiftInformation': { 'shift1': { 'color': 'red' , 'amount'

我一直在寻找解决问题的方法,但找不到任何适用的方法。我正在尝试将一个高维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.DataFrame(json)
  • json_规范化(json)
  • pd.read_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
)
等等


对于如何解决这一问题的任何建议,我们都将不胜感激。

我通过将dict展平,提出了一个数据帧:

将熊猫作为pd导入
def flat_dict(字典,前缀):
如果类型(字典)=dict:
行=[]
对于键,字典中的项。项()
行+=平底(项目,前缀+[键])
返回行
其他:
返回[前缀+[字典]]
定义dict_to_df(字典):
返回pd.DataFrame(平面dict(字典,[]))

当然,由于
json
包,您需要首先将json作为dict导入。

一个可能的解决方案:一旦您将json展平到一个数据帧,您可以通过
将标签拆分为新列。您希望每一行都是
shiftX
?因此,第1行是
shift1
,第2行是
shift2
,等等?您可以共享整个json文件吗?或者至少是你想要的2行数据?熊猫数据框不擅长处理层次数据。它们具有类似CSV文件或Excel电子表格的行和列的概念,因此您应该决定数据帧的外观,使用
json加载json。加载
,以适合
pd.dataframe
的格式将其转换为2D数据,并从中构建数据帧。