gpt4 book ai didi

python - 如何将 ndarray 的 dtype 更改为 numpy 中的自定义类型?

转载 作者:太空狗 更新时间:2023-10-30 02:49:34 25 4
gpt4 key购买 nike

我做了一个 dtype 是:

mytype = np.dtype([('a',np.uint8), ('b',np.uint8), ('c',np.uint8)])

所以数组使用这个数据类型:

test1 = np.zeros(3, dtype=mytype)

测试 1 是:

array([(0, 0, 0), (0, 0, 0), (0, 0, 0)],
dtype=[('a', '|u1'), ('b', '|u1'), ('c', '|u1')])

现在我有测试2:

test2 = np.array([[1,2,3], [4,5,6], [7,8,9]])

当我使用 test2.astype(mytype) 时,结果不是我想要的:

array([[(1, 1, 1), (2, 2, 2), (3, 3, 3)],
[(4, 4, 4), (5, 5, 5), (6, 6, 6)],
[(7, 7, 7), (8, 8, 8), (9, 9, 9)]],
dtype=[('a', '|u1'), ('b', '|u1'), ('c', '|u1')])

我想要的结果是:

array([(1, 2, 3), (4, 5, 6), (7, 8, 9)],
dtype=[('a', '|u1'), ('b', '|u1'), ('c', '|u1')])

有什么办法吗?谢谢。

最佳答案

您可以使用 numpy.core.records 的 fromarrays 方法(参见 documentation ):

np.rec.fromarrays(test2.T, mytype)
Out[13]:
rec.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)],
dtype=[('a', '|u1'), ('b', '|u1'), ('c', '|u1')])

数组必须先转置,因为函数将数组的行视为输出中结构化数组的列。另见这个问题:Converting a 2D numpy array to a structured array

关于python - 如何将 ndarray 的 dtype 更改为 numpy 中的自定义类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7644597/

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