Convert JSON file to Pandas dataframe

后端 未结 4 1492
醉话见心
醉话见心 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-10 00:00

    Nested JSONs are always quite tricky to handle correctly.

    A few months ago, I figured out a way to provide an "universal answer" using the beautifully written flatten_json_iterative_solution from here: which unpacks iteratively each level of a given json.

    Then one can simply transform it to a Pandas.Series then Pandas.DataFrame like so:

    df = pd.Series(flatten_json_iterative_solution(dict(json_))).to_frame().reset_index()
    

    Intermediate Dataframe result

    Some data transformation can easily be performed to split the index in the columns names you asked for:

    df[["index", "col1", "col2", "col3", "col4"]] = df['index'].apply(lambda x: pd.Series(x.split('_')))
    

    Final result

提交回复
热议问题