Adding a column to dataframe without changing its name

Hello. So I was playing around with data frames and wanted to know how I can add columns to my existing dataframe without having to create/define a new one. For eg. let’s say I have a dataframe df0 with the columns x,y,z and wanted to add a new column t=y-x. The code df0.Define("t", "y-x") does nothing. I am running this in interactive mode/directly on the terminal after running root -l so any help will be appreciated.

Hello,
You just need to assign df0 to the result of Define(), ie:

df0 = df0.Define("t", "y-x")

Here’s a minimal example using the terminal:

root [0] ROOT::RDataFrame rdf(100);
root [1] auto rdf_x = rdf.Define("x", [](){ return gRandom->Rndm(); });
root [2] rdf_x.Display()->Print()
+-----+----------+
| Row | x        | 
+-----+----------+
| 0   | 0.999742 | 
+-----+----------+
| 1   | 0.162910 | 
+-----+----------+
| 2   | 0.282618 | 
+-----+----------+
| 3   | 0.947201 | 
+-----+----------+
| 4   | 0.231657 | 
+-----+----------+
root [3] rdf_x = rdf_x.Define("y", [](){ return gRandom->Rndm(); });
root [4] rdf_x.Display()->Print()
+-----+----------+----------+
| Row | x        | y        | 
+-----+----------+----------+
| 0   | 0.484974 | 0.957477 | 
+-----+----------+----------+
| 1   | 0.744305 | 0.540044 | 
+-----+----------+----------+
| 2   | 0.739953 | 0.759944 | 
+-----+----------+----------+
| 3   | 0.658637 | 0.315638 | 
+-----+----------+----------+
| 4   | 0.804403 | 0.519672 | 
+-----+----------+----------+
root [5] rdf_x = rdf_x.Define("t", "y-x")
(ROOT::RDF::RInterface<ROOT::Detail::RDF::RLoopManager, void> &) @0x7fef6de0a000
root [6] rdf_x.Display()->Print()
+-----+-----------+----------+----------+
| Row | t         | x        | y        | 
+-----+-----------+----------+----------+
| 0   | 0.306957  | 0.168572 | 0.475530 | 
+-----+-----------+----------+----------+
| 1   | -0.170646 | 0.392314 | 0.221668 | 
+-----+-----------+----------+----------+
| 2   | -0.182855 | 0.213190 | 0.030335 | 
+-----+-----------+----------+----------+
| 3   | -0.139390 | 0.333539 | 0.194149 | 
+-----+-----------+----------+----------+
| 4   | -0.363785 | 0.943717 | 0.579932 | 
+-----+-----------+----------+----------+
1 Like