如何在numpy中将ndarray的数据类型更改为自定义类型?

4

我创建了一个数据类型,它是:

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

因此,使用这种数据类型的数组:

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

test1是:

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

现在我有了test2:

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

I want the result to be:

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

有什么方法吗?谢谢。
3个回答

5
你可以使用numpy.core.records的fromarrays方法(请参阅文档):
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')])

数组必须首先进行转置,因为该函数将数组的行视为输出结构化数组的列。另请参见此问题:将2D numpy数组转换为结构化数组

0

因为所有的字段都是相同类型,所以您也可以使用以下代码:

>>> test2.astype(np.uint8).view(mytype).squeeze(axis=-1)
array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], 
      dtype=[('a', 'u1'), ('b', 'u1'), ('c', 'u1')])

需要进行压缩,因为test2是二维的,但你想要一个一维的结果


0
在创建数组时,如果输入的可迭代对象包含元组(保证是不可变的),而不是列表(保证是可变的),那么只要每个元组中的项数等于结构体中字段的数量,它就会自动按照您所需的方式接受输入。
In[7]: test2 = np.array([(1,2,3), (4,5,6), (7,8,9)], dtype = mytype)

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

对于仅此而言,无需去使用 np.rec 等函数。但是如果输入的可迭代对象包含列表而不是元组,则 numpy 不会像您期望的那样逐个获取字段并进行数据复制。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接