Adding a new branch to each entry using PyROOT, but the number of entries doubles

Hello everyone, I came across a ROOT dataset while studying, and I’m trying to add two new branches to a TTree, which are arrays,without changing the numbers of entries.
I ran the following code, but in the end, my number of entries doubled, and the arrays were filled with very small numbers close to zero.
My coding skills are not very strong, and I can’t figure out where the problem might be. Could anyone please provide me with some help?

import ROOT
def add_double_array_branch(root_file_path):
    # Open the ROOT file in update mode
    root_file = ROOT.TFile(root_file_path, "UPDATE")

    # Access the tree inside the ROOT file
    tree1 = root_file.Get("TreeAna")

    leaf_point1 = tree1.GetLeaf("point")
    leaf_trk1 = tree1.GetLeaf("n_trk")
    leaf_gam1 = tree1.GetLeaf("n_gam")

    # Create a new branch with TArrayD data type
    trkarray1 = ROOT.TArrayD()
    gamarray1 = ROOT.TArrayD()
    trk_branch1 = tree1.Branch("trkpoint", trkarray1, "trkpoint[n_trk]/D")
    gam_branch1 = tree1.Branch("gampoint", gamarray1, "gampoint[n_gam]/D")

    # Assign arrays to the new branch
    for i in range(tree1.GetEntries()):
        tree1.GetEntry(i)

        #read n_trk and n_gam, and set as the length of array
        trk_value1 = leaf_trk1.GetValue()
        gam_value1 = leaf_gam1.GetValue()
        trkarray1.Set(int(trk_value1))
        gamarray1.Set(int(gam_value1))

        # Fill the new branch with double values
        for j in range(int(trk_value1)):
            trkarray1[j] = point_value1
        for j in range(int(gam_value1)):
            gamarray1[j] = point_value1
        trk_branch1.SetAddress(trkarray1)
        gam_branch1.SetAddress(gamarray1)

        # Fill the tree with the new branch
        tree1.Fill()

    tree1.Write("", ROOT.TObject.kOverwrite)
    root_file.Close()

Hi @sty1900012423,
welcome on the ROOT forum!
Did you try RDataFrame? You can easily define new columns and Snapshot the dataset in a ttree in a file. Here the tutorial showing these features.

Cheers,
Monica

thank you for your help!
i will have a try later!

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