gpt4 book ai didi

python - 改变结构化/记录数组的数据类型

转载 作者:太空宇宙 更新时间:2023-11-04 01:38:01 25 4
gpt4 key购买 nike

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')])

最佳答案

Q1:np.arraynp.astype 方法在底层以相同的方式完成相同的工作。使用 np.astype 需要更少的输入,并且读者可以更清楚地知道其意图是更改数据类型。

关于python - 改变结构化/记录数组的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7941591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com