【问题标题】:How to convert nested json structure having varying list (as dictionary values) to dataframe如何将具有不同列表(作为字典值)的嵌套 json 结构转换为数据框
【发布时间】:2020-03-15 20:29:40
【问题描述】:

我将 JSON 转换为 DataFrame 并最终得到一个列“Structure_value”,其中包含以下值作为字典/字典列表:

                   Structure_value
[{'Room': [6], 'Length': 7}, {'Room': [6], 'Length': 7}]
[{'Room': [6], 'Length': 22}]
[{'Room': [6,6], 'Length': 8}]

我需要把它分成以下四列:

Structure_value_room_1 结构值长度_1 Structure_value_room_2 结构值长度_2

这个的输出应该如下:

   Structure_value_room_1  Structure_value_length_1  Structure_value_room_2  \
0                       6                         7                     6.0   
1                       6                        22                     NaN   
2                       6                         8                     6.0   

   Structure_value_length_2  
0                       7.0  
1                       NaN  
2                       8.0  

如何处理单个属性在单个列表中有多个值并且我们需要将它们拆分到其他列的情况。

P.S.:我能够处理这种数据如下的情况:[{'Room': [6], 'Length': 7}, {'Room': [6], 'Length': 7}],但我无法处理这种情况[{'Room': [6,6], 'Length': 8}]

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我无法将您的 Structure_value 演示文稿作为 json 文件处理,我不知道它们是否代表许多单个文件。 我使用 [{'Room': [6], 'Length': 7}, {'Room': [6], 'Length': 7}] 作为 file1 和 [{'Room': [6], 'Length ': 22}] 作为 file2 和 [{'Room': [6,6], 'Length': 8}] 作为 file3。

    #treat the irregular structures
    def process_structure(s):
    
        specs = []
    
        for label,quantity in s.items():
    
            if isinstance(quantity,list):       
                specs.append(label)
                for elem in quantity:
                    specs.append(elem)          
            elif isinstance(quantity,int):
                specs.append(label)
                specs.append(quantity)
    
        return specs
    
    #open and treat jsons
    def treat_json(file):
    
        with open(file, 'r') as f:
    
            dicts   = {}
            to_df   = []
            load_df = []
    
            valRoom = 0
            valLen  = 0
    
            structures = json.load(f)
    
            for dicts in structures:
    
                to_df = process_structure(dicts)
                long  = len(to_df) 
    
                for i in range(0,long):
    
                    if to_df[i] == 'Room':
                        valRoom = to_df[i+1]
                        load_df.append(valRoom)
                    elif to_df[i] == 'Length':
                        valLen = to_df[i+1]
                        load_df.append(valLen)
                    elif isinstance(to_df[i],int) and i < (long - 1):
                        if isinstance(to_df[i+1],int):
                            load_df.append(to_df[i+1])
                            load_df.append(valLen)#repeat Length
    
            while len(load_df) < 4: #if its no complete
                load_df.append(None)
    
            df_temp = pd.DataFrame([load_df],columns=['Structure_value_room_1','Structure_value_length_1','Structure_value_room_2','Structure_value_length_2'])
    
        return df_temp
    

    那是印刷品:

    treat_json('house3.json')
        Structure_value_room_1  ...  Structure_value_length_2
    0                       6  ...                         8
    
    [1 rows x 4 columns]
    
    treat_json('house2.json')
        Structure_value_room_1  ...  Structure_value_length_2
    0                       6  ...                      None
    
    [1 rows x 4 columns]
    
    treat_json('house1.json')
    
        Structure_value_room_1  ...  Structure_value_length_2
    0                       6  ...                         7
    
    [1 rows x 4 columns]
    

    【讨论】:

      【解决方案2】:

      如果我们谈论这种特殊的数据结构,我希望这会有所帮助。

      源数据

      s_v = [[{'Room': [6], 'Length': 7}, {'Room': [6], 'Length': 7}],[{'Room': [6], 'Length': 22}], [{'Room': [6,6], 'Length': 8}]]
      df = pd.DataFrame({'Structure_value':s_v})
      df
      
      Out[1]:
      
          Structure_value
      0   [{'Room': [6], 'Length': 7}, {'Room': [6], 'Le...
      1   [{'Room': [6], 'Length': 22}]
      2   [{'Room': [6, 6], 'Length': 8}]
      

      标准化

      df['tmp'] = df['Structure_value'].apply(lambda x: [{'Room':[v], 'Length': x[0]['Length']} for v in x[0]['Room']] if ((len(x) == 1) & (type(x[0]['Room'])==list)) else x)
      pd.DataFrame(df['tmp'].values.tolist())
      
      Out[2]:
      
           0                            1
      0   {'Room': [6], 'Length': 7}    {'Room': [6], 'Length': 7}
      1   {'Room': [6], 'Length': 22}   None
      2   {'Room': [6], 'Length': 8}    {'Room': [6], 'Length': 8}
      

      您说这种数据结构适合您进行后续处理。

      【讨论】:

        猜你喜欢
        • 2021-03-03
        • 2021-12-21
        • 1970-01-01
        • 1970-01-01
        • 2022-09-27
        • 1970-01-01
        • 2020-03-07
        • 2020-03-31
        • 1970-01-01
        相关资源
        最近更新 更多