2012-03-30 51 views
9

有几个职位,几乎回答这个,但我不明白他们或他们不回答这个问题:如何更改numpy recarray的dtype?

我有使用numpy.rec.fromrecords进行recarray。说我想将某些列转换为浮动。我该怎么做呢?我应该换成一个ndarray并且他们回到一个recarray?

回答

14

下面是使用astype来执行转换的示例:

import numpy as np 
recs = [('Bill', '31', 260.0), ('Fred', 15, '145.0')] 
r = np.rec.fromrecords(recs, formats = 'S30,i2,f4', names = 'name, age, weight') 
print(r) 
# [('Bill', 31, 260.0) ('Fred', 15, 145.0)] 

age是D型细胞<i2的:

print(r.dtype) 
# [('name', '|S30'), ('age', '<i2'), ('weight', '<f4')] 

我们可以使用astype改变,要<f4

r = r.astype([('name', '|S30'), ('age', '<f4'), ('weight', '<f4')]) 
print(r) 
# [('Bill', 31.0, 260.0) ('Fred', 15.0, 145.0)] 
+0

谢谢! “astype”比重新创建一个新的数组稍微更紧凑......我认为它在效率方面达到了相同的效果。我在下面发布我的解决方案,因为它包括如何修改现有的dtype。 – mathtick 2012-04-05 14:37:46

11

有一个基本上分两步。我的绊脚石是找到如何修改现有的dtype。这是我做到的:

# 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)