Writing a 2D array with pyroot

Hi all,

I want to write a 2D array (vector < vector >) in a tree with pyroot and I’m facing some issues. I followed the suggestions from here: https://root-forum.cern.ch/t/store-2d-array-into-ttree-use-python/27530/2

The problem is that using the following lines as suggested in the reply does not work for my setup:

n = np.array(2, dtype=np.int32)
t.Branch('mynum', n, 'mynum/I')
x = np.array([[1., 2., 3.], [4., 5., 6.]])
t.Branch('myarray', x, 'myarray[2][3]/D')

This does not work in my case because I have a 2D array where the size of the “inner vector” is not fixed. Therefore I cannot use something like the following line where the dimension “3” is fixed

t.Branch('myarray', x, 'myarray[mynum][3]/D')

With the C++ API this is straightforward, something like this:

std::vector< std::vector< double > > example_vec
fTree->Branch( "example_vec", &example_vec );

Do you know how to do this with pyroot?

Thanks a lot,
Adam

JupyROOT==6.24.6
ROOT==6.24.6

Hello,

According to:

t.Branch('mynum', n, 'mynum/I')
t.Branch('myarray', x, 'myarray[mynum][3]/D')

is not officially supported but “might work”. I guess you’ve tried already and there was no luck?

Another thing you could try is RVec:

https://root.cern/doc/master/classROOT_1_1VecOps_1_1RVec.html

If you look at the python docs in the link above, RVecs can adopt the memory of a numpy array. Once transformed into a (flat) RVec, you could then store it as with a vector branch. When retrieving it from the file, you would be able to retransform it into a numpy array with asarray but you’d also need to reshape it to get the original shape.

(note however that to do RVec I/O outside of RDataFrame you will want ROOT v6.26, see ROOT Version 6.24 Release Notes )

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