Convert list of tuples to structured numpy array

前端 未结 1 2019
闹比i
闹比i 2020-12-14 02:01

I have a list of Num_tuples tuples that all have the same length Dim_tuple

xlist = [tuple_1, tuple_2, ..., tuple_Num_tuples]


        
相关标签:
1条回答
  • 2020-12-14 02:36

    A list of tuples is the correct way of providing data to a structured array:

    In [273]: xlist = [(1, 1.1), (2, 1.2), (3, 1.3)]
    
    In [274]: dt=np.dtype('int,float')
    
    In [275]: np.array(xlist,dtype=dt)
    Out[275]: 
    array([(1, 1.1), (2, 1.2), (3, 1.3)], 
          dtype=[('f0', '<i4'), ('f1', '<f8')])
    
    In [276]: xarr = np.array(xlist,dtype=dt)
    
    In [277]: xarr['f0']
    Out[277]: array([1, 2, 3])
    
    In [278]: xarr['f1']
    Out[278]: array([ 1.1,  1.2,  1.3])
    

    or if the names are important:

    In [280]: xarr.dtype.names=['name1','name2']
    
    In [281]: xarr
    Out[281]: 
    array([(1, 1.1), (2, 1.2), (3, 1.3)], 
          dtype=[('name1', '<i4'), ('name2', '<f8')])
    

    http://docs.scipy.org/doc/numpy/user/basics.rec.html#filling-structured-arrays

    0 讨论(0)
提交回复
热议问题