我有一个必须保持其dtype固定的数组。但是,在追加语句之后,其dtype会更改。如何在不更改dtype的情况下附加值?
vertices = array([0.5, 0.0, 0.0, 1.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0, 1.0, 0.0,
0.0, -0.5, 0.0, 0.0, 0.5, 0.0], dtype=np.float32)
print(vertices.dtype)
vertices = append(vertices, [-0.5, 0.0, 0.0, 0.0, 0.0, 1.0])
print(vertices.dtype)
输出: float32 float64
答案 0 :(得分:2)
from numpy import *
import numpy as np
vertices = array([0.5, 0.0, 0.0, 1.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0, 1.0, 0.0,
0.0, -0.5, 0.0, 0.0, 0.5, 0.0], dtype=np.float32)
print(vertices.dtype)
vertices = append(vertices, np.array([-0.5, 0.0, 0.0, 0.0, 0.0, 1.0], dtype=np.float32))
print(vertices.dtype)
random_arr = [-0.5, 0.0, 0.0, 0.0, 0.0, 1.0]
print(np.array(random_arr).dtype)
float32
float32
float64
默认情况下,numpy在float数组上分配float64数据类型(检查最后一个random_arr),因此,一旦连接一个float32和一个float64数组,显然最终数组将被强制转换为float64。因此,为安全起见,只需在创建numpy数组时指定dtype。
答案 1 :(得分:1)
您可以将新数据附加为numpy数组,并在转换时传入类型。
import numpy as np
vertices = np.array([0.5, 0.0, 0.0, 1.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0, 1.0, 0.0,
0.0, -0.5, 0.0, 0.0, 0.5, 0.0], dtype=np.float32)
print(vertices.dtype)
vertices = np.append(vertices, np.array([-0.5, 0.0, 0.0, 0.0, 0.0, 1.0], dtype=np.float32))
print(vertices.dtype)