代码之家  ›  专栏  ›  技术社区  ›  Alex Luya

如何将元组列表转换为元组的numpy数组?

  •  16
  • Alex Luya  · 技术社区  · 8 年前

    我有这样一个列表:

    l=[(1,2),(3,4)]
    

    我想将其转换为numpy数组,并将数组项类型保持为元组:

    array([(1,2),(3,4)])
    

    但是numpy。数组(l)将给出:

    array([[1,2],[3,4)]])
    

    项目类型已从元组更改为numpy。ndarray,然后我指定了项目类型

    numpy.array(l,numpy.dtype('float,float'))
    

    这将提供:

     array([(1,2),(3,4)])
    

    但项类型不是tuple,而是numpy。无效,所以问题是:

     how to convert it to a numpy.array of tuple,not of numpy.void? 
    
    2 回复  |  直到 6 年前
        1
  •  23
  •   Divakar    8 年前

    你可以有一个数组 object dtype,让数组的每个元素都是一个元组,如下所示-

    out = np.empty(len(l), dtype=object)
    out[:] = l
    

    样本运行-

    In [163]: l = [(1,2),(3,4)]
    
    In [164]: out = np.empty(len(l), dtype=object)
    
    In [165]: out[:] = l
    
    In [172]: out
    Out[172]: array([(1, 2), (3, 4)], dtype=object)
    
    In [173]: out[0]
    Out[173]: (1, 2)
    
    In [174]: type(out[0])
    Out[174]: tuple
    
        2
  •  6
  •   SuperCodeBrah    5 年前

    出于某种原因,如果您正在寻找一行代码,您不能简单地这样做(即使Divakar的答案最终留给您 dtype=object

    np.array([(1,2),(3,4)], dtype=object)
    

    相反,你必须这样做:

    np.array([(1,2),(3,4)], dtype="f,f")
    

    "f,f" "i,i" 对于整数)。如果需要,可以通过添加 .astype(object) 到上面一行的末尾)。