Converting a 2D numpy array to a structured array

前端 未结 5 1664
故里飘歌
故里飘歌 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条回答
  •  -上瘾入骨i
    2020-11-29 01:54

    You can "create a record array from a (flat) list of arrays" using numpy.core.records.fromarrays as follows:

    >>> import numpy as np
    >>> myarray = np.array([("Hello",2.5,3),("World",3.6,2)])
    >>> print myarray
    [['Hello' '2.5' '3']
     ['World' '3.6' '2']]
    
    
    >>> newrecarray = np.core.records.fromarrays(myarray.transpose(), 
                                                 names='col1, col2, col3',
                                                 formats = 'S8, f8, i8')
    
    >>> print newrecarray
    [('Hello', 2.5, 3) ('World', 3.5999999046325684, 2)]
    

    I was trying to do something similar. I found that when numpy created a structured array from an existing 2D array (using np.core.records.fromarrays), it considered each column (instead of each row) in the 2-D array as a record. So you have to transpose it. This behavior of numpy does not seem very intuitive, but perhaps there is a good reason for it.

提交回复
热议问题