Convert structured array with various numeric data types to regular array

后端 未结 4 1274
天命终不由人
天命终不由人 2021-01-06 11:24

Suppose I have a NumPy structured array with various numeric datatypes. As a basic example,

my_data = np.array( [(17, 182.1),  (19, 175.6)],  dtype=\'i2,f4\         


        
4条回答
  •  不思量自难忘°
    2021-01-06 12:05

    A variation on Warren's answer (which copies data by field):

    x = np.empty((my_data.shape[0],len(my_data.dtype)),dtype='f4')
    for i,n in enumerate(my_data.dtype.names):
        x[:,i]=my_data[n]
    

    Or you could iterate by row. r is a tuple. It has to be converted to a list in order to fill a row of x. With many rows and few fields this will be slower.

    for i,r in enumerate(my_data):
        x[i,:]=list(r)
    

    It may be instructive to try x.data=r.data, and get an error: AttributeError: not enough data for array. x data is a buffer with 4 floats. my_data is a buffer with 2 tuples, each of which contains an int and a float (or sequence of [int float int float]). my_data.itemsize==6. One way or other, the my_data has to be converted to all floats, and the tuple grouping removed.

    But using astype as Jaime shows does work:

    x.data=my_data.astype('f4,f4').data
    

    In quick tests using a 1000 item array with 5 fields, copying field by field is just as fast as using astype.

提交回复
热议问题