简体   繁体   English

如何在 python 中建树?

[英]How to build a tree in python?

I've been futzing around with the anytree and treelib libraries for the last few days, but I can't figure out how to actually build the tree.在过去的几天里,我一直在研究 anytree 和 treelib 库,但我不知道如何实际构建树。 I'm sure there's something relatively simple I'm missing.我确定我缺少一些相对简单的东西。 Basically, I need to build an org chart.基本上,我需要建立一个组织结构图。 My data consists of two lists:我的数据包含两个列表:

df = {'employee_id': {0: 'XFV67DN9Z',
  1: 'LGUW9GHUL',
  2: 'ZI2ZN7GRB',
  3: '3JUJVPMOX',
  4: 'XSRDWVMRW',
  5: '9QVJI1VYI',
  6: 'K22VHQ6AG',
  7: 'KL5D81665'},
 'manager_id': {0: 0,
  1: 'XFV67DN9Z',
  2: 'XFV67DN9Z',
  3: 'XFV67DN9Z',
  4: 'ZI2ZN7GRB',
  5: 'XFV67DN9Z',
  6: 'XFV67DN9Z',
  7: 'XFV67DN9Z'}}

The first employee is the CEO, so they represent the root node.第一个员工是 CEO,所以他们代表根节点。 I need to build a tree with potentially 1000s of employees.我需要建立一棵可能有 1000 名员工的树。 Each node also has to contain attributes like gender, salary, etc. (which will also be stored in columns).每个节点还必须包含性别、薪水等属性(也将存储在列中)。 If I could assign these attributes while building the tree, that would be ideal.如果我可以在构建树时分配这些属性,那将是理想的。 The goal for the tree structure is to be able to analyze things with regard to layers of the org.树结构的目标是能够分析有关组织层的事物。 So, for example, what is the average number of children at layer 3 of the org?那么,例如,组织第 3 层的孩子的平均数量是多少? Or, what is the average salary at level 9. I'm not quite sure how I'll do these calculations yet, but I'm just trying to get the data structure built so I can get to that part...或者,第 9 级的平均工资是多少。我不太确定我将如何进行这些计算,但我只是想建立数据结构,以便我可以进入那部分......

Ideally, if there's a library that I could use to make this more straightforward that would be great.理想情况下,如果有一个库可以用来使这更简单,那就太好了。 I looked into anytree but couldn't figure out how to iterate through the node creation process to create the tree.我查看了anytree,但不知道如何遍历节点创建过程来创建树。 Treelib posed the same problem. Treelib 提出了同样的问题。 Any advice?有什么建议吗?

Ended up using the networkx library which can be found here:最终使用了 networkx 库,可以在这里找到:

https://networkx.github.io/ https://networkx.github.io/

Specifically, the from_pandas_dataframe method makes this very easy:具体来说, from_pandas_dataframe 方法使这非常容易:

https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.convert_matrix.from_pandas_dataframe.html https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.convert_matrix.from_pandas_dataframe.ZFC35FDC70D5FC69D269883A82

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

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