# Merging two TTrees with different variables but 1 common key

**URL:** <https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861>\
**Category:** Newbie\
**Tags:** rdataframe\
**Created:** [July 28, 2023, 12:36pm UTC](https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861 "2023-07-28T12:36:07Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![helton](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/h/8797f3/32.png) [@helton](https://root-forum.cern.ch/u/helton)\
**Post date:** [July 28, 2023, 12:36pm UTC](https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861/1 "2023-07-28T12:36:08Z")

</div>

Hi everyone. I have 2 TTrees t1 and t2 from 1 .root file. I created a RDataFrame for each tree and now want to merge them. The trees contain different variables and have different amount of coloums as a rdf. But they have 1 common key variable that they share per event. I managed to do this successfully in pandas dataframe, but I want to try it in RDataFrame. The code I used with pandas was simply:

```auto
df_combined = pd.merge(df_t1, df_t2)

```

where I didnt have to specifiy the common key, because its the only common variable, so pd.merge takes it automatically.

I was now wondering how I could do the same in RDataFrame.  
Because I didnt find a something like .Merge in the documentation. Would one way be to friend the trees? But it wouldnt really friend them along a common key or is an option for that?

Thanks for any help.

\_ROOT Version: JupyROOT 6.28/00

---

<div class="post-metadata">

**Author:** ![eguiraud](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/eguiraud/32/32217_2.png) [@eguiraud](https://root-forum.cern.ch/u/eguiraud)\
**Post date:** [July 31, 2023, 5:10pm UTC](https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861/2 "2023-07-31T17:10:14Z")

</div>

Hello @helton ,

RDataFrames cannot be merged.

> [@helton](#):
>
> Would one way be to friend the trees? But it wouldnt really friend them along a common key or is an option for that?

That’s exactly it, the way is using _indexed_ friend trees. This makes me realize we should add a section to the RDF docs that shows an example. Here’s how you do it, the magic happens thanks to the `BuildIndex` call:

```python
import ROOT

main_file = ROOT.TFile.Open("main.root")
mainTree = main_file.Get("mainTree")

aux_file = ROOT.TFile.Open("aux.root")
aux_tree = aux_file.Get("auxTree")

# if a friend tree has an index on `commonColumn`, when the main tree loads
# a given row, it then loads the row of the friend tree that has the same value
# of `commonColumn`   
aux_tree.BuildIndex("commonColumn")

mainTree.AddFriend(aux_tree)

df = ROOT.RDataFrame(mainTree)

```

I realize it’s a bit clunkier than the pandas version but it comes with having to deal with a more complex/powerful data format that larger-than-memory datasets.

Cheers,  
Enrico

P.S.  
note that there was [a bug](https://github.com/root-project/root/issues/12260) in using indexed friend trees with multi-threading in ROOT v6.28.00 – it is fixed in v6.28.02 or later.

---

<div class="post-metadata">

**Author:** ![helton](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/h/8797f3/32.png) [@helton](https://root-forum.cern.ch/u/helton)\
**Post date:** [July 31, 2023, 5:24pm UTC](https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861/3 "2023-07-31T17:24:41Z")

</div>

Hi Enrico,

thanks so much! This solves my issue.

Cheers

---

<div class="post-metadata">

**Author:** ![eguiraud](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/eguiraud/32/32217_2.png) [@eguiraud](https://root-forum.cern.ch/u/eguiraud)\
**Post date:** [August 2, 2023, 6:20pm UTC](https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861/4 "2023-08-02T18:20:48Z")

</div>

P.S.  
I just opened [a PR to improve the docs](https://github.com/root-project/root/pull/13385)

---

<div class="post-metadata">

**Author:** ![helton](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/h/8797f3/32.png) [@helton](https://root-forum.cern.ch/u/helton)\
**Post date:** [September 6, 2023, 2:44pm UTC](https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861/5 "2023-09-06T14:44:33Z")

</div>

Hi Enrico,

I have trouble getting this to work for multipe files. They are all of same shape and the trees are also called the same.  
Doing .Get() doesnt work for lists of files. What can I do then? I tried to create a TChain for each tree and just append the other TChains from the other files to it:

```auto
chain_main = ROOT.TChain("t_main")
chain_aux = ROOT.TChain("t_aux")
for infile in inFiles:
    chain_main.AddFile(infile)
    chain_aux.AddFile(infile)
chain_main.BuildIndex("eventNumber")
chain_aux.BuildIndex("eventNumber")
chain_main.AddFriend(chain_aux)

rdf=ROOT.RDataFrame(chain_reco)

```

(It takes a very long time (I have around 15 files)) But then I get errors, that:  
Error in TChainIndex::TChainIndex: The indices in files of this chain aren’t sorted.  
Error in TTreePlayer::BuildIndex: Creating a TChainIndex unsuccessful - switching to TTreeIndex

So how can I just do it with TTreeIndex then?

Sorry for opening the post up again, but I thought it was still close to the original topic.  
Cheers

---

<div class="post-metadata">

**Author:** ![eguiraud](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/eguiraud/32/32217_2.png) [@eguiraud](https://root-forum.cern.ch/u/eguiraud)\
**Post date:** [September 6, 2023, 2:58pm UTC](https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861/6 "2023-09-06T14:58:05Z")

</div>

Hi @helton ,

which line fails exactly? Do you need to construct the RDataFrame object to observe the issue? Note that you don’t need to call `BuildIndex` on the main chain, only on the friend (and `RDataFrame(chain_reco)` should be `RDataFrame(chain_main)`).

Cheers,  
Enrico

---

<div class="post-metadata">

**Author:** ![helton](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/h/8797f3/32.png) [@helton](https://root-forum.cern.ch/u/helton)\
**Post date:** [September 11, 2023, 5:52pm UTC](https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861/7 "2023-09-11T17:52:19Z")

</div>

Hi Enrico,

its not really an error, its like a warning message so it doesnt specify a line directly. It produces like 10 of these lines I posted, I guess 1 for each adding file or so?

But I do get the error even without constructing the rdf. Any idea?

Cheers

---

<div class="post-metadata">

**Author:** ![eguiraud](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/eguiraud/32/32217_2.png) [@eguiraud](https://root-forum.cern.ch/u/eguiraud)\
**Post date:** [September 11, 2023, 7:04pm UTC](https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861/8 "2023-09-11T19:04:23Z")

</div>

> [@helton](#):
>
> it doesnt specify a line directly

Yes but you can play with the code a bit to figure out at which line the error is printed. For example you can put printouts in-between lines to track execution, or run the code in a debugger one line at a time.

Also as I mentioned you don’t need to call `BuildIndex` on the main chain, only on the friend, does that help?

---

<div class="post-metadata">

**Author:** ![helton](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/h/8797f3/32.png) [@helton](https://root-forum.cern.ch/u/helton)\
**Post date:** [September 12, 2023, 11:15am UTC](https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861/9 "2023-09-12T11:15:56Z")

</div>

Hi Enrico,

taking out the 1 line of BuildIndex essentially takes out half of the error warnings. So instead of this:

```auto
Error in TChainIndex::TChainIndex: The indices in files of this chain aren’t sorted.
Error in TChainIndex::TChainIndex: The indices in files of this chain aren’t sorted.
... (this 10 times)
 Error in TTreePlayer::BuildIndex: Creating a TChainIndex unsuccessful - switching to TTreeIndex

Error in TChainIndex::TChainIndex: The indices in files of this chain aren’t sorted.
Error in TChainIndex::TChainIndex: The indices in files of this chain aren’t sorted.
... (this 10 times)
 Error in TTreePlayer::BuildIndex: Creating a TChainIndex unsuccessful - switching to TTreeIndex

```

I only get half of this so only once. So the error line has to be the chain.BuildIndex right? It gives one line error per file im adding to the chain.

Does something like this work instead?  
Add the trees from the files into the rdf:

```auto
frame = RDataFrame("TTreeName", "filename*")

```

and index/friend it afterwards or something?

Cheers

---

<div class="post-metadata">

**Author:** ![eguiraud](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/eguiraud/32/32217_2.png) [@eguiraud](https://root-forum.cern.ch/u/eguiraud)\
**Post date:** [September 12, 2023, 1:57pm UTC](https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861/10 "2023-09-12T13:57:50Z")

</div>

Hi @helton ,

alright so we confirmed this is not related to RDataFrame but it’s a TChain issue, and if I understand correctly the following should be a reproducer:

```python
chain_aux = ROOT.TChain("t_aux")
for infile in inFiles:
    chain_aux.AddFile(infile)
chain_aux.BuildIndex("eventNumber")

```

We need @pcanal 's help to figure out what the problem is exactly, let’s ping him.

Please share a minimal set of input files (maybe 2-3 are enough) that we can use to reproduce the problem on our side and debug it.

About your last question, the indexing and the friendship needs to be set up outside of RDF.

Cheers,  
Enrico

---

<div class="post-metadata">

**Author:** ![helton](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/h/8797f3/32.png) [@helton](https://root-forum.cern.ch/u/helton)\
**Post date:** [September 13, 2023, 10:18am UTC](https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861/11 "2023-09-13T10:18:36Z")

</div>

Hi Enrico,  
yes this exactly produces the error messages I talked about. I will send you a link to 3 input files.

Cheers

---

<div class="post-metadata">

**Author:** ![pcanal](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/pcanal/32/12439_2.png) [@pcanal](https://root-forum.cern.ch/u/pcanal)\
**Post date:** [September 13, 2023, 2:08pm UTC](https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861/12 "2023-09-13T14:08:32Z")

</div>

The type of the message is misleading, it is actually more of a Warning.

`TChainIndex` has a optimization that speed ups the lookup significantly by require the index value to increase monotonous “accross” files (eg so it knows that it never needs to go backward once it reach a certain index value).

To avoid the message (and end up with the exact same result as you do now with the error message) do:  
(after translating it to Python)

```auto
auto t = new TTreeIndex( chain ,"eventNumber","");
if (t->IsZombie()) {
   ... print error message ...
   delete t;
   return error_code;
}

```

---

<div class="post-metadata">

**Author:** ![helton](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/h/8797f3/32.png) [@helton](https://root-forum.cern.ch/u/helton)\
**Post date:** [September 14, 2023, 1:36pm UTC](https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861/13 "2023-09-14T13:36:08Z")

</div>

Hello pcanal,

thanks for clarifying!

Cheers

---

<div class="post-metadata">

**Author:** ![curious\_goose](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/c/958977/32.png) [@curious\_goose](https://root-forum.cern.ch/u/curious_goose)\
**Post date:** [February 11, 2025, 5:50am UTC](https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861/14 "2025-02-11T05:50:51Z")

</div>

@pcanal I am using this from python and I see the same problem. How should the code below

```python
chain = TChain(treename)
for file in file_paths:
      chain.Add(file)

chain.BuildIndex('EVENTNUMBER', 'RUNNUMBER')

```

be changed? The index building line sporadically makes the code crash. I have checked that:

- All files have the two indexing columns
- The two chains that I make friends have the same number of entries.

I cannot make sure that these branches increase monotonically.

---

<div class="post-metadata">

**Author:** ![curious\_goose](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/c/958977/32.png) [@curious\_goose](https://root-forum.cern.ch/u/curious_goose)\
**Post date:** [February 11, 2025, 6:14am UTC](https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861/15 "2025-02-11T06:14:17Z")

</div>

@pcanal Regarding the efficiency of this method, I am pretty sure there must be an algorithm out there that prevents the computer to go back and forth to find matches. Can’t you just loop over the main chain and build a hash table between the entry in the main tree and some hash made from `EVENTNUMBER` and `RUNNUMBER`?

Then when you loop over the other trees, you just make the hash for each entry and match them. Am I missing anything? If not, this should have been done many years ago.

BTW, chatGPT just told me that:

```python
chain = TChain(treename)
for file in files:
     self._check_tree(file)
      chain.Add(file)

index = TTreeIndex(chain, 'EVENTNUMBER', 'RUNNUMBER')
chain.SetTreeIndex(index)

```

should work and it seems to be working.

---

<div class="post-metadata">

**Author:** ![curious\_goose](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/c/958977/32.png) [@curious\_goose](https://root-forum.cern.ch/u/curious_goose)\
**Post date:** [February 11, 2025, 11:15am UTC](https://root-forum.cern.ch/t/merging-two-ttrees-with-different-variables-but-1-common-key/55861/16 "2025-02-11T11:15:37Z")

</div>

Nevemind, I am still seeing random crashes when doing this, unfortunately I cannot give you our trees to reproduce the problem, they have around 60Gb and are not public data.
