简体   繁体   中英

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. 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. I need to build a tree with potentially 1000s of employees. 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? 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...

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. Treelib posed the same problem. Any advice?

Ended up using the networkx library which can be found here:

https://networkx.github.io/

Specifically, the from_pandas_dataframe method makes this very easy:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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