pandas groupby to nested json

后端 未结 4 939
再見小時候
再見小時候 2020-11-27 05:47

I often use pandas groupby to generate stacked tables. But then I often want to output the resulting nested relations to json. Is there any way to extract a nested json fil

4条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 06:23

    I had a look at the solution above and figured out that it only works for 3 levels of nesting. This solution will work for any number of levels.

    import json
    levels = len(grouped.index.levels)
    dicts = [{} for i in range(levels)]
    last_index = None
    
    for index,value in grouped.itertuples():
    
        if not last_index:
            last_index = index
    
        for (ii,(i,j)) in enumerate(zip(index, last_index)):
            if not i == j:
                ii = levels - ii -1
                dicts[:ii] =  [{} for _ in dicts[:ii]]
                break
    
        for i, key in enumerate(reversed(index)):
            dicts[i][key] = value
            value = dicts[i]
    
        last_index = index
    
    
    result = json.dumps(dicts[-1])
    

提交回复
热议问题