2013-03-08 2 views
3

다른 목록 크기와 유형의 중첩 목록이 있습니다. 이벤트의 예에 대한 결과중첩 목록을 numpy 배열로 변환하는 효율적인 방법

def read(f,tree,objects): 

Event=[] 
for o in objects: 
    #find different features of one class 
    temp=[i.GetName() for i in tree.GetListOfBranches() if i.GetName().startswith(o)] 
    tempList=[] #contains one class of objects 
    for t in temp: 
     #print t 
     tempList.append(t) 
     comp=np.asarray(getattr(tree,t)) 
     tempList.append(comp) 
Event.append(tempList) 

return Event 



def main(): 
    path="path/to/file" 
    objects= ['TauJet', 'Jet', 'Electron', 'Muon', 'Photon', 'Tracks', 'ETmis', 'CaloTower'] 

    f=ROOT.TFile(path) 
    tree=f.Get("RecoTree") 
    tree.GetEntry(100) 
    event=read(f,tree,objects) 

[0] I는 NumPy와 배열로 변환하는 방법

['TauJet', array(1), 'TauJet_E', array([ 31.24074173]), 'TauJet_Px', array([-28.27997971]), 'TauJet_Py', array([-13.18042469]), 'TauJet_Pz', array([-1.08304048]), 'TauJet_Eta', array([-0.03470514]), 'TauJet_Phi', array([-2.70545626]), 'TauJet_PT', array([ 31.20065498]), 'TauJet_Charge', array([ 1.]), 'TauJet_NTracks', array([3]), 'TauJet_EHoverEE', array([ 1745.89221191]), 'TauJet_size', array(1)] 

입니까?

참고 1 : np.asarray (이벤트, "개체")가 느립니다. 나는 더 나은 길을 찾고있다. 또한 고정 된 유형이없는 한 np.fromiter()는 적용 할 수 없습니다.

참고 2 : 내 이벤트의 길이를 알지 못합니다.

주 3 : 작업을 쉽게하면 이름을 타볼 수도 있습니다.

+2

내가 pandas''에서 모양을 제공하도록 제안 ['DataFrames'] (http://pandas.pydata.org/pandas-docs/stable/dsintro.html). 다른 길이의 컬럼에 대한 지원이 있다는 것을 (어쩌면 올바르게) 기억하고 있습니다. 게다가 그들은 numpy 수치 연산을 지원합니다. –

답변

1

이런 식으로 시도해 볼 수 있습니다. 얼마나 빠를 지 잘 모르겠습니다. 이렇게하면 첫 번째 행에 대해 numpy 레코드 배열이 만들어집니다.

data = event[0] 
keys = data[0::2] 
vals = data[1::2] 
#there are some zero-rank arrays in there, so need to check for those, 
#but I think just recasting them to a np.float should work. 
temp = [np.float(v) for v in vals] 
#you could also just create a np array from the line above with np.array(temp) 
dtype={"names":keys, "formats":("f4")*len(vals)} 
myArr = np.rec.fromarrays(temp, dtype=dtype) 

#test it out 
In [53]: data["TauJet_Pz"] 
Out[53]: array(-1.0830404758453369, dtype=float32) 


#alternatively, you could try something like this, which just creates a 2d numpy array 
vals = np.array([[np.float(v) for v in row[1::2]] for row in event]) 
#now create a nice record array from that using the dtypes above 
myRecordArray = np.rec.fromarrays(vals, dtype=dtype) 
+0

이 작업을 수행 할 수 없습니다. 내가 말했듯이 나는 다른 길이의리스트를 가지고있다. 그래서 여기에 언급 한 것과 다른 길이의 항목이있을 때 temp2 = [v in v 용] TypeError : 길이가 1 인 배열 만 파이썬 스칼라 으로 변환 할 수 있으며이 길이까지도 가능합니다. 나는 얻는다 : fromarrays에있는 "/usr/lib/pymodules/python2.7/numpy/core/records.py"파일 5335, myArr = np.rec.fromarrays (temp2, dtype = dtype) descr =TypeError : 데이터 형식을 알 수 없음 – Moj

+0

[ "TauJet_E", array ([31.56, 45.14])]와 같은 여러 요소가있는 행에 배열이있는 것처럼 들립니다. 그것은 당신이 보는 오류를 재현 할 것입니다. 그게 왜 그랬을까요? – reptilicus

+0

내 코드는 내가 질문에 올린 것과 정확히 같습니다! 내가 말했듯이, vectore의 길이는 내가 할 때 (comp = np.asarray (getattr (tree, t))) 객체마다 다를 수있다. 예를 들어 내가 가지고있을 수 있습니다 : 'Jet_E', 배열 ([391.62017822, 31.24074173]), v.astype (float)을 사용하여이 문제를 해결했지만 여전히 TypeError 문제가 있습니다. 마지막 부분에서 이해할 수없는 데이터 형식 – Moj

관련 문제