From this dataframe:
tree cues directions thresholds exits
1 PLC2hrOGTT;Age;BMI;TimesPregnant >;>;>;> 126;29;29.7;6 1;0;1;0.5
2 PLC2hrOGTT;Age;BMI >;>;> 126;29;29.7 0;1;0.5
3 PLC2hrOGTT;Age;BMI;TimesPregnant >;>;>;> 126;29;29.7;6 1;0;0;0.5
4 PLC2hrOGTT;Age;BMI;TimesPregnant >;>;>;> 126;29;29.7;6 1;1;0;0.5
5 PLC2hrOGTT;Age;BMI;TimesPregnant >;>;>;> 126;29;29.7;6 0;1;0;0.5
6 PLC2hrOGTT;Age;BMI >;>;> 126;29;29.7 0;0;0.5
7 PLC2hrOGTT;Age;BMI;TimesPregnant >;>;>;> 126;29;29.7;6 1;1;1;0.5
8 PLC2hrOGTT;Age;BMI;TimesPregnant >;>;>;> 126;29;29.7;6 0;0;0;0.5
with this code:
>>> def row_to_tree(row):
... out = {}
... pos = [out]
... for cues, directions, thresholds, exits in zip(*map(lambda x: x.split(";"), row[["cues", "directions", "thresholds", "exits"]].values)):
... pos = pos[0]
... pos["cues"] = cues
... pos["directions"] = directions
... pos["thresholds"] = thresholds
... pos["exits"] = exits
... pos["children"] = [{"cues":True}]
... pos = pos["children"]
... pos.append({"cues": False})
... return out
I can get this desired output:
>>> trees = [row_to_tree(row) for i, row in df.iterrows()]
>>> print(json.dumps(trees[0], indent=2))
{
"cues": "PLC2hrOGTT",
"directions": ">",
"thresholds": "126",
"exits": "1",
"children": [
{
"cues": "Age",
"directions": ">",
"thresholds": "29",
"exits": "0",
"children": [
{
"cues": "BMI",
"directions": ">",
"thresholds": "29.7",
"exits": "1",
"children": [
{
"cues": "TimesPregnant",
"directions": ">",
"thresholds": "6",
"exits": "0.5",
"children": [
{
"cues": true
},
{
"cues": false
}
]
}
]
}
]
}
]
}
but I want now to add an if statement inside this loop, so what I want now when I add the children I want an if there so that if the exits==1 first add True and then the child and if it's not then first add the child and then add False. (i.e. the parent 'PLC2hrOGTT' should have "cues": True and then "cues": "Age" because "exits": is "1" in 'PLC2hrOGTT) Can I achieve this in this loop?
This is the desired output:
{
"cues": "PLC2hrOGTT",
"directions": ">",
"thresholds": "126",
"exits": "1",
"children": [
{
"cues": "True",
},
{
"cues": "Age",
"directions": ">",
"thresholds": "29",
"exits": "0",
"children": [
{
"cues": "BMI",
"directions": ">",
"thresholds": "29.7",
"exits": "1",
"children": [
{
"cues": "True",
},
{
"cues": "TimesPregnant",
"directions": ">",
"thresholds": "6",
"exits": "0.5",
"children":[
{
"cues": "True"
},
{
"cues": "False"
}
]
}
]
},
{
"cues": "False"
}
]
}
]
}
Aucun commentaire:
Enregistrer un commentaire