Saving numpy arrays into TTrees

Dear ROOT developers,

I am facing some issues converting data from a given format to TTrees through python.
Unfortunately what I could found on the forum and the web did not help me to solve the issue. Most probably it is due to my inexperience with Python, but I would be glad if you could help me or point me to the right source.

I have some files which I can access through python. I loop over them and each iteration gives me a numpy array which I would like to store as an entry in a Tree in order to proceed the analysis with C++ afterwards. Unfortunately, when I access the tree I see either empty values of the array or random ones. The issue is reproduced by the following code:

import ROOT as R
import numpy as np

F = R.TFile("outTest.root", "RECREATE")
T = R.TTree ("DATA", "DATA")

arr = np.zeros((5,), dtype=np.float32)
T.Branch("arr", arr, "arr[5]/F")
for i in range(5):
    arr = np.array([x*i for x in range(5)], dtype=np.float32)
    T.Fill()

T.Write()
F.Close()

No errors are prompted, but the values saved to the root file are not the right ones.
The for loop mimics the iteration over several files, and at each iteration the array is modified. What is the correct way to proceed?

Best regards,
Loris


Please read tips for efficient and successful posting and posting code

_ROOT Version 6.24
_Platform: MacOS and Linux


Hello,

I believe the issue is that while you are defining your branch to point to arr:

arr = np.zeros((5,), dtype=np.float32)
T.Branch("arr", arr, "arr[5]/F")

inside the loop you are rebinding arr to a new array (and the previous one is garbage collected):

for i in range(5):
    arr = np.array([x*i for x in range(5)], dtype=np.float32)
    T.Fill()

could you try to do arr[:] = np.array([x*i for x in range(5)], dtype=np.float32) so that the same array space is kept and just overwritten with new content?

2 Likes

i agree with that

Works like a charm!

Thank you very much,
Loris

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