Logo ROOT   6.18/05
Reference Guide
pyroot001_arrayInterface.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_pyroot
3## \notebook -nodraw
4## This tutorial illustrates the conversion of STL vectors and TVec to numpy
5## arrays without copying the data.
6## The memory-adoption is achieved by the dictionary __array_interface__, which
7## is added dynamically to the Python objects by PyROOT.
8##
9## \macro_code
10##
11## \date April 2018
12## \author Stefan Wunsch
13
14import ROOT
15from sys import exit
16
17try:
18 import numpy as np
19except:
20 exit()
21
22# Create a vector ROOT object and assign values
23# Note that this works as well with a TVec
24vec = ROOT.std.vector("float")(2)
25vec[0] = 1
26vec[1] = 2
27print("Content of the ROOT vector object: {}".format([x for x in vec]))
28
29# Interface ROOT vector with a numpy array
30array = np.asarray(vec)
31print("Content of the associated numpy array: {}".format([x for x in array]))
32
33# The numpy array adopts the memory of the vector without copying the content.
34# Note that the first entry of the numpy array changes when assigning a new
35# value to the first entry of the ROOT vector.
36vec[0] = 42
37print(
38 "Content of the numpy array after changing the first entry of the ROOT vector: {}".
39 format([x for x in array]))
40
41# Use numpy features on data of ROOT objects
42print("Mean of the numpy array entries: {}".format(np.mean(array)))