Convert JSON file to Pandas dataframe

后端 未结 4 1495
醉话见心
醉话见心 2021-02-09 23:40

I would like to convert a JSON to Pandas dataframe.

My JSON looks like: like:

{ 
   \"country1\":{ 
      \"AdUnit1\":{ 
         \"floor_price1\":{ 
            


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-02-09 23:49

    Not the best way, but it's work. Also you should modify flatten function that is only picked from this awnser

    test = { 
       "country1":{ 
          "AdUnit1":{ 
             "floor_price1":{ 
                "feature1":1111,
                "feature2":1112
             },
             "floor_price2":{ 
                "feature1":1121
             }
          },
          "AdUnit2":{ 
             "floor_price1":{ 
                "feature1":1211
             },
             "floor_price2":{ 
                "feature1":1221
             }
          }
       },
       "country2":{ 
          "AdUnit1":{ 
             "floor_price1":{ 
                "feature1":2111,
                "feature2":2112
             }
          }
       }
    }
    
    from collections import defaultdict
    import pandas as pd
    import collections
    
    def flatten(d, parent_key='', sep='_'):
        items = []
        for k, v in d.items():
            new_key = parent_key + sep + k if parent_key else k
            if isinstance(v, collections.MutableMapping):
                items.extend(flatten(v, new_key, sep=sep).items())
            else:
                items.append((new_key, v))
        return dict(items)
    
    results = defaultdict(list)   
    colnames = ["col1", "col2", "col3", "col4", "col5", "col6"]
    for key, value in flatten(test).items():
        elements = key.split("_")
        elements.append(value)
        for colname, element in zip(colnames, elements):
            results[colname].append(element)
    
    df = pd.DataFrame(results)
    print(df)
    

提交回复
热议问题