Logo ROOT  
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## \macro_output
11##
12## \date April 2018
13## \author Stefan Wunsch
14
15import ROOT
16from sys import exit
17
18try:
19 import numpy as np
20except:
21 exit()
22
23# Create a vector ROOT object and assign values
24# Note that this works as well with a TVec
25vec = ROOT.std.vector("float")(2)
26vec[0] = 1
27vec[1] = 2
28print("Content of the ROOT vector object: {}".format([x for x in vec]))
29
30# Interface ROOT vector with a numpy array
31array = np.asarray(vec)
32print("Content of the associated numpy array: {}".format([x for x in array]))
33
34# The numpy array adopts the memory of the vector without copying the content.
35# Note that the first entry of the numpy array changes when assigning a new
36# value to the first entry of the ROOT vector.
37vec[0] = 42
38print(
39 "Content of the numpy array after changing the first entry of the ROOT vector: {}".
40 format([x for x in array]))
41
42# Use numpy features on data of ROOT objects
43print("Mean of the numpy array entries: {}".format(np.mean(array)))