How to change the dtype of certain columns of a numpy recarray?

前端 未结 3 1922
鱼传尺愫
鱼传尺愫 2020-12-06 01:35

Suppose I have a recarray such as the following:

import numpy as np

# example data from @unutbu\'s answer
recs = [(\'Bill\', \'31\', 260.0), (\'Fred\', 15,          


        
3条回答
  •  一个人的身影
    2020-12-06 02:21

    There are basically two steps. My stumbling block was in finding how to modify an existing dtype. This is how I did it:

    # change dtype by making a whole new array
    dt = data.dtype
    dt = dt.descr # this is now a modifiable list, can't modify numpy.dtype
    # change the type of the first col:
    dt[0] = (dt[0][0], 'float64')
    dt = numpy.dtype(dt)
    # data = numpy.array(data, dtype=dt) # option 1
    data = data.astype(dt)
    

提交回复
热议问题