ROOT
v6-24
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
15
import
ROOT
16
from
sys
import
exit
17
18
try
:
19
import
numpy
as
np
20
except
:
21
exit()
22
23
# Create a vector ROOT object and assign values
24
# Note that this works as well with a TVec
25
vec = ROOT.std.vector(
"float"
)(2)
26
vec[0] = 1
27
vec[1] = 2
28
print(
"Content of the ROOT vector object: {}"
.format([x
for
x
in
vec]))
29
30
# Interface ROOT vector with a numpy array
31
array = np.asarray(vec)
32
print(
"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.
37
vec[0] = 42
38
print(
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
43
print(
"Mean of the numpy array entries: {}"
.format(np.mean(array)))
tutorials
pyroot
pyroot001_arrayInterface.py
ROOT v6-24 - Reference Guide Generated on Fri Jan 27 2023 03:32:43 (GVA Time) using Doxygen 1.9.5