pyROOT not filling the tree correctly when the branch is array

Here is an example code:

from ROOT import TFile, TTree
import numpy as np

f = TFile('example.root', 'recreate')
t = TTree('mytree', 'example tree')

x = np.zeros((2,3))
t.Branch('myarray', x, 'myarray[2][3]/D')

nentries = 25
for i in range(nentries):
   x = np.array([[1+i, 2.+i, 3.+i], [4.+i, 5.+i, 6.+i]])


I got expected root file when uncommenting “print(x)” (up plot), but got wrong root file when “print(x)” is commented (down plot).

_ROOT Version:_root_v6.26.06
Platform: MAC OS 12.5.1
Compiler: Not Provided


The problem is probably that you are setting x inside the loop and thus you are rebinding it to another array. What you should do instead is to reuse the same x (the one you passed to Branch) and modify it inside the loop. Rebinding x just causes the previous array to be garbage collected and the variable will point now to a new place in memory, which is different than what Branch received.

Makes sense. Thank you!

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