首页 > 解决方案 > 对特定索引应用 .astype() 不起作用

问题描述

我想在 dnarray 中将第一列更改为 int

print(gcp)

[[ 1. 6.218 2.974 0. ] [ 2. 32.881 8.66 0. ] [ 3.
38.94 35.843 0. ] [ 4. 8.52 35.679 0. ] [ 5. 52.902 49.538 0. ]]

print(gcp.dtype)

浮动64

gcp[:,0] = (gcp[:,0]).astype(int)
print(((gcp[:,0]).astype(int)).dtype)

整数32

print(gcp.dtype)

浮动64

我尝试使用 deepcopy,但没有成功。任何帮助都会很好,我没有发现任何类似的问题。

标签: pythonnumpy

解决方案


只拥有index of the row(+1)数组的 as 元素对我来说似乎是多余的,也许您根本不需要第一行。否则对我来说最好的选择是使用两个数组:

gcp0 = gcp[:, 0].astype(int)
gcp = gcp[:, 1:]

另一种可能性是为单独的列named fields分别定义单独dtypes的列,这可能使您更接近pandas,这是您拥有的另一个选项。

gcp = np.array([(1., 6.218,  2.974,  0.),
                (2., 32.881, 8.66,   0.),
                (3., 38.94,  35.843, 0.),
                (4., 8.52,   35.679, 0.),
                (5., 52.902, 49.538, 0.)],
                dtype={'names':   ['index', 'a0', 'a1', 'a2'],
                       'formats': [int, float, float, float]})

print(gcp['index'])
# [1 2 3 4 5]

推荐阅读