2011-10-04 2 views
4

내가되는 DTYPE했다 :numpy에서 ndarray의 dtype을 맞춤 1로 변경하는 방법은 무엇입니까?

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

그래서 DTYPE 사용하여 어레이 :

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

ㅁㅁ

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

어떤 방법이 있나요 내가 test2.astype(mytype)를 사용하는 도중, 결과는 내가되고 싶은 것이 아니다? 감사.

답변

5

당신은 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')]) 

어레이는 제 transposd되어야하는 함수 구조화의 열로 배열의 행과 관련 때문에 출력에 배열. 모든 필드는 동일한 유형이기 때문에 Converting a 2D numpy array to a structured array

0

, 당신은 또한 사용할 수 있습니다 :이 질문을 참조하십시오 test2은 2D이기 때문에 압박이 필요

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

을,하지만 당신은 1D 결과를 원

관련 문제