在python中从列表遍历树进行计算?

2024-10-03 19:25:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下清单:

new_tree = {'cues': 'glucose_tol',
  'directions': '<=',
  'thresholds': '122.5',
  'exits': 1.0,
  'children': [{'cues': True},
   {'cues': 'mass_index',
    'directions': '<=',
    'thresholds': '30.8',
    'exits': 1.0,
    'children': [{'cues': 'pedigree',
      'directions': '<=',
      'thresholds': '0.305',
      'exits': 1.0,
      'children': [{'cues': True},
       {'cues': 'diastolic_pb',
        'directions': '<=',
        'thresholds': '77.0',
        'exits': 1,
        'children': [{'cues': True}, 
        {'cues': 'insulin',
         'directions': '<=',
         'thresholds': '480',
         'exits': '0.5',
         'children': [{'cues': True}, {'cues': False}]}]}]}]}]}

我想得到这些数据点在树列表中的路径,这样我就可以知道它们的位置,然后进行一些计算

我在df中有数据点(2个数据点仅用于说明):

print(df)

times_pregnant,glucose_tol,diastolic_pb,triceps,insulin,mass_index,pedigree,age,label
6,148,72,35,0,33.6,0.627,50,1
1,85,66,29,0,26.6,0.351,31,0

第一个是血糖、体重指数、谱系、舒张压,并被归类为真。如何从该数据点所经过的列表中获取这4个提示,并将其保存以备将来计算?任何帮助都将不胜感激


Tags: 数据trueindexmasschildrenpbtolpedigree
1条回答
网友
1楼 · 发布于 2024-10-03 19:25:26

这看起来像一个决策树

它的工作方式是,在每个步骤中,您要么处于最终决策状态(“提示”:True,要么“提示”:false),要么需要做出决策

要做出决定,您需要从数据帧中获取名为“cues”的字段,然后使用方向和阈值形成一个条件。第一个基本上是if glucose_tol <= 122.5。每个节点都应该有2个子节点,我认为第一个子节点是正确的,第二个子节点是错误的(如果你知道这个域,这对你来说应该很明显)。然后根据您的决定选择孩子继续

可能最简单的方法是实现一个递归函数。一旦您有了根据一行数据评估树的功能,您就可以添加功能来存储您想要的或您认为有趣的内容

相关问题 更多 >