2012-03-30 62 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)