How to get NbinsX with pyroot?

Hi, I want to get NbinsX in python , the code is

import ROOT
from ROOT import gRandom, TH1, TH1D, TH2D, TCanvas
fdata=ROOT.TFile.Open(“data.root”)
fbkg = ROOT.TFile.Open(“bkg.root”)

hdata = fdata.Get(“z_pt”)
hbkg = fbkg.Get(“z_pt”)

h1=hdata
for i in range(1,len(hdata.GetNbinsX())+1):
content = hdata.GetBinContent(i)-hbkg.GetBinContent(i)
h1.SetBinContent(i,content)

c1 = ROOT.TCanvas(“c1”, “c1”,5,50,500,500)
c1.SetLogy()
h1.Draw("")
c1.SaveAs(“zpt.png”)

but there is an error:
Traceback (most recent call last):
File “r1.py”, line 16, in
for i in range(1,len(hdata.GetNbinsX())+1):
AttributeError: ‘TObject’ object has no attribute ‘GetNbinsX’

Do you have some suggestion?

Hi @Jen,

It sems that the type that you are expecting from fdata.Get("z_pt") is a THn class, but you are getting a plain TObject. I will invite @etejedor to this thread; he will be able to shed some light on this.

Cheers,
J.

Hi,

I don’t think casting TObject to a THn is necessary in PyROOT. Try changing

for i in range(1,len(hdata.GetNbinsX())+1):

to

for i in range(1, hdata.GetNbinsX()+1):

instead.

Just a guess, but in principle in Root you can use (in C macros) Get<Class>('key')
If you know in advance the type of the object you take, you can try with

hdata = f.Get["TH1D"]("z_pt")

Hello,

The reason might be that z_pt can’t be retrieved from data.root, so what you get back is an (empty) TObject.

Can you do:

hdata = fdata.Get(“z_pt”)
print(hdata)

What does it print?

Another thing you can try is:

hdata = fdata.z_pt

Does it throw an attribute error?

Hi,
I found that ‘z_pt’ can’t be retrieved from ‘data.root’, because there is some problem with the root file.
Thanks for your solution.
And thanks for all of you!
Cheers

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