1
Q1。將列重新設置爲不同的數據類型時,是否優先使用np.array
或np.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')])
謝謝!這是令人驚訝的,因爲Python的禪宗......「應該有一個 - 最好只有一個 - 明顯的方法來做到這一點。」當我有更多的觀點時,我會回來並且注意觀看...... – hatmatrix