Pandas - expand nested json array within column in dataframe

前端 未结 3 989
礼貌的吻别
礼貌的吻别 2021-02-05 17:17

I have a json data (coming from mongodb) containing thousands of records (so an array/list of json object) with a structure like the below one for each object:

{         


        
3条回答
  •  长情又很酷
    2021-02-05 17:37

    I propose an interesting answer I think using pandas.json_normalize.
    I use it to expand the nested json -- maybe there is a better way, but you definitively should consider using this feature. Then you have just to rename the columns as you want.

    import io
    from pandas import json_normalize
    
    # Loading the json string into a structure
    json_dict = json.load(io.StringIO(json_str))
    
    df = pd.concat([pd.DataFrame(json_dict), 
                    json_normalize(json_dict['nested_array_to_expand'])], 
                    axis=1).drop('nested_array_to_expand', 1)
    

提交回复
热议问题