2011-10-29 28 views
1

Q1。将列重新设置为不同的数据类型时,是否优先使用np.arraynp.astype?我见过使用np.astype的例子,但都似乎返回了所需的结果(都返回原始数组的副本)。更改结构化/记录阵列的类型

import numpy as np 

## recasting string to integer 
x = np.rec.array([('a','1'),('b','2')],names='col1,col2') 
## 
In []: x 
Out[]: 
rec.array([('a', '1'), ('b', '2')], 
     dtype=[('col1', '|S1'), ('col2', '|S1')]) 
## 
dt = x.dtype.descr 
dt[1] = (dt[1][0],'int') 
## which is more appropriate: 
y = np.array(x,dtype=dt) 
## or 
y = x.astype(dt) 
## ? 
In []: y 
Out[]: 
rec.array([('a', 1), ('b', 2)], 
     dtype=[('col1', '|S1'), ('col2', '<i4')]) 

Q2。重命名列:调用np.array时,整数列变为零,但保留其值np.rec.array。为什么?我的理解是,对于前者,你得到一个结构化数组,而后者返回一个记录数组;对于大多数目的,我认为他们是一样的。无论如何,这种行为令人惊讶。

## rename 2nd column from col2 to v2 
dt = copy.deepcopy(y.dtype) 
names = list(dt.names) 
names[1] = 'v2' 
dt.names = names 
## this is not right 
newy = np.array(y,dtype=dt) 
In []: newy 
Out[]: 
array([('a', 0), ('b', 0)], 
     dtype=[('col1', '|S1'), ('v2', '<i4')]) 
## this is correct 
newy = np.rec.array(y,dtype=dt) 
In []: newy 
Out[]: 
rec.array([('a', 1), ('b', 2)], 
     dtype=[('col1', '|S1'), ('v2', '<i4')]) 

回答

2

Q1:无论是np.arraynp.astype方法做下引擎罩以同样的方式同样的工作。使用np.astype涉及少一点打字,读者更清楚打算改变数据类型。

+0

谢谢!这是令人惊讶的,因为Python的禅宗......“应该有一个 - 最好只有一个 - 明显的方法来做到这一点。”当我有更多的观点时,我会回来并且注意观看...... – hatmatrix