繁体   English   中英

如何从 pandas dataframe 在 ZA7F5F35426B527411FCZ92321

[英]How to produce hierarchical JSON tree from pandas dataframe in Python

我想编写一个 function,它根据 JSON 数据返回一棵树。

这是 pandas dataframe:

employee_id     designation     department      name      manager_emp_id
1                co-founder      co-founder      john         2
2                ceo             co-founder      rocky       
3                cto             tech            alfred       2
4                sde3            tech            bruce        3
5                sde1            tech            tony         4
6                cmo             marketing       steve        2
7                sde1            tech            bucky        3

这是我正在寻找的树的一个例子:

       ceo 
    /   |  \
   /    |   \
 cto   cmo   coo 
  |      |     \
  |      |      \
 sde3  sales   operative executives
  |
  |
 sde1 

Output 格式:

所需 Output

{
    employee_id : 2, 
    name : rocky, 
    reportees : [
                    {
                        employee_id : 3, 
                        name : alfred, 
                        reportees:[....]
                    }
                ]
}

您可以使用递归:

d = [{'employee_id': 1, 'designation': 'co-founder', 'department': 'co-founder', 'name': 'john', 'manager_emp_id': 2}, {'employee_id': 2, 'designation': 'ceo', 'department': 'co-founder', 'name': 'rocky', 'manager_emp_id': ''}, {'employee_id': 3, 'designation': 'cto', 'department': 'tech', 'name': 'alfred', 'manager_emp_id': 2}, {'employee_id': 4, 'designation': 'sde3', 'department': 'tech', 'name': 'bruce', 'manager_emp_id': 3}, {'employee_id': 5, 'designation': 'sde1', 'department': 'tech', 'name': 'tony', 'manager_emp_id': 4}, {'employee_id': 6, 'designation': 'cmo', 'department': 'marketing', 'name': 'steve', 'manager_emp_id': 2}, {'employee_id': 7, 'designation': 'sde1', 'department': 'tech', 'name': 'bucky', 'manager_emp_id': 3}]
def get_tree(_id = ''):
   return [{'employee_id':i['employee_id'], 
            'name':i['name'], 
            **({} if not (rp:=get_tree(i['employee_id'])) else {'reportees':rp})} 
            for i in d if i['manager_emp_id'] == _id]

print(get_tree())

Output:

[{'employee_id': 2, 'name': 'rocky', 'reportees': [{'employee_id': 1, 'name': 'john'}, {'employee_id': 3, 'name': 'alfred', 'reportees': [{'employee_id': 4, 'name': 'bruce', 'reportees': [{'employee_id': 5, 'name': 'tony'}]}, {'employee_id': 7, 'name': 'bucky'}]}, {'employee_id': 6, 'name': 'steve'}]}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM