PYROOT: Fill histogram with numpy array

I am trying out PYROOT for the first time. I need to fill several histograms with numpy arrays read from data files and then fit them.

However, I am getting an error at the point where I try to fill the histogram with the array. I am sharing a simplified code that reproduces the same problem.

import numpy as np
import ROOT as root

x= np.random.rand(1,100)

h1   = root.TH1D( 'h1', 'Test random', 100, 0., 1.5 )
h1.Fill(x)

c = root.TCanvas()
c.Draw()
h1.Draw()

When I run this, I get the error:

>>> h1.Fill(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: none of the 3 overloaded methods succeeded. Full details:
  int TH1::Fill(double x) =>
    could not convert argument 1 (only size-1 arrays can be converted to Python scalars)

I have also tried using ctypes (which I do not fully understand) by filling the histogram int the following way. But I still get an error.

import ctypes
xnew=x.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
h1.Fill(xnew)

This gives the following error.

>>> h1.Fill(xnew)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: none of the 3 overloaded methods succeeded. Full details:
  int TH1::Fill(double x) =>
    could not convert argument 1 (a float is required)

What am I doing wrong? Is there a simple way to fill a histogram with a numpy array?


Please read tips for efficient and successful posting and posting code

ROOT Version: ROOT 6.19/01 - using PYROOT
Platform: Kubuntu 16.04
Compiler: Not Provided


Actually, I have just managed to fill it by creating a loop.

for xeach in x[0]:
    print xeach
    h1.Fill(xeach)

I think that I got my python and my ROOT mixed up for a while.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.