如何在Python中将json树数据转换为数据帧?

时间:2017-05-23 08:40:03

标签: python json pandas tree

我有一个json数据可以表示为树结构,每个节点有四个属性:nameidchildparentid(pid)(对于叶节点)它只有三个属性:idpidname)。

{'child': [{'id': '','child':[{'id': '','child':['name':'','id':'','pid':''], 'name': '', 'pid':''}], 'name': '', 'pid': ''}],'name':'','pid':'','id':''}

我想将其转换为具有三列的数据框,如:

    id, pid, name
1   .., ..., ....
2   .., ..., ....

使用来自三个属性(id,pid,name)

的所有图层的数据

我已尝试使用默认参数pandas.read_json,但似乎无法迭代整个图层,输出就像:

    id, pid, name, child
1   .., ..., ...., {'id':'','pid': '','name': '', 'child':[{...}]}
2   .., ..., ...., {'id':'','pid': '','name': '', 'child':[{...}]}

我想知道是否有一些简单的方法可以使用或不使用pandas来解决此问题。

1 个答案:

答案 0 :(得分:0)

我使用递归来实现它,并且我已经证明它适用于我的数据。

import json
import pandas as pd


def test_iterate(df):
    global total_data
    total_data = total_data.append(df[['id','pid','name']])
    try:
        df['child'].apply(lambda x:test_iterate(pd.DataFrame(x)))
    except Exception as inst:
        print(inst)
        pass

if __name__ == '__main__':
    total_data = pd.DataFrame()
    loaddata = json.load(open('test.json'))
    df = pd.DataFrame(loaddata)
    test_iterate(df)
    total_data.to_csv('test.csv',index=None)