How to change the leaf values of certain branch and save in the root file?

Dear experts,

I want to change all the leaf values of branch “isSignal” from nan to 0, leaving other values unchanged and save as an updated root file. I have tried a lot using python, but i can only read the values with pointers but change them. I also tried delete the orginal branch and then created a same one, but i didn’t manage to do that, the values i write seems not the case i think, and i can not open the modified root file with “*** Break *** segmentation violation”. Could you help me sove this problem?
Please see my code below:

branch = tree.GetBranch(“isSignal”)
isSignal = array.array(‘I’, [ 0 ])
tmp_branch = tree.Branch(“isSignal”, isSignal, “isSignal/I”)
for i in range(tree.GetEntries()):
– isSignal[0]=0
– tmp_branch.Fill()

ROOT Version: 6.24/00
Platform: linux
Compiler: g++ (GCC) 10.2.0

Dear @waxili ,

Unfortunately you are not even checking whether the current value of your branch is nan or otherwise in your snippet above, so you know that won’t give you the result you expect.

I recommend RDataFrame

import ROOT

# Saves a TTree with 10 entries to disk with one branch "x". First 5 values == 11,
# other 5 values == 22.
df = ROOT.RDataFrame(10).Define("x", "rdfentry_ < 5 ? 11 : 22").Snapshot("tree","file.root")
# Show the current values in the column
df.Display(["x"], 10).Print()

# Redefine your "x" column with the updated values depending on your condition
df = df.Redefine("x", "x == 11 ? 44 : 22")

# Show the updated values in the column
df.Display(["x"], 10).Print()

# Now you can save your updated TTree to new file
df.Snapshot("tree", "updated.root")

Note that you will need at least ROOT 6.26 for the Redefine operation.


1 Like

Thank you for the reply, but i’m using a cluster where i can’t update the version of ROOT.

The reason i don’t check the leaf values is that i already know they are nan, and i want to replace them with 0. Is this check important or just a minor problem among others?

I have managed to do this! Below shows the code:

    newtree = tree.CloneTree(0)
    isSignal = array.array('d', [ 0 ])
    newtree.SetBranchAddress("isSignal", isSignal)
    for i in range(tree.GetEntries()):

I think pointer in python can handle nan values, values can be read out and overwrite. The real trick that bothers me is actually the CloneTree() which can clone an empty tree instead of copy the whole list (CopyTree()) so that we can fill and write in the empty new tree and replace the original tree with it.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.