Converting a 2D numpy array to a structured array

前端 未结 5 1686
故里飘歌
故里飘歌 2020-11-29 01:08

I\'m trying to convert a two-dimensional array into a structured array with named fields. I want each row in the 2D array to be a new record in the structured array. Unfortu

5条回答
  •  心在旅途
    2020-11-29 01:35

    There's a lot of confusion here between "record array" and "structured array". Here's my short solution for a structured array.

    dtype = np.dtype([("Col1","S8"),("Col2","f8"),("Col3","i8")])
    myarray = np.array([("Hello",2.5,3),("World",3.6,2)], dtype=dtype)
    np.array(np.rec.fromarrays(myarray.transpose(), names=dtype.names).astype(dtype=dtype).tolist(), dtype=dtype)
    

    So, with the assumption that dtype is defined, this is a one-liner.

提交回复
热议问题