진박사의 일상

[Python3] numpy에서 dictionary처럼 쓸 수 있는 Structured Array 본문

프로그래밍

[Python3] numpy에서 dictionary처럼 쓸 수 있는 Structured Array

진박사. 2021. 6. 5. 15:27

python의 dictionary 자료 구조는 데이터를 관리하기 무척 편하게 해준다.

그러나 numpy에서는 dictionary 구조가 없다. 대신 이와 비슷한 Structured Array라는 것이 존재한다.

 

Structured arrays — NumPy v1.10 Manual (scipy.org)

 

Structured arrays — NumPy v1.10 Manual

Defining Structured Arrays One defines a structured array through the dtype object. There are several alternative ways to define the fields of a record. Some of these variants provide backward compatibility with Numeric, numarray, or another module, and sh

docs.scipy.org

 

import numpy as np

d_type = ([('id','i4'), ('distance','f8')])
distances = np.zeros(10, dtype=d_type)
'''
array([(0, 0.), (0, 0.), (0, 0.), (0, 0.), (0, 0.), (0, 0.), (0, 0.),
       (0, 0.), (0, 0.), (0, 0.)],
      dtype=[('id', '<i4'), ('distance', '<f8')])
'''

간단히 말해서 dtype으로 [(속성명1, 속성타입1),(속성명2, 속성타입2)...)]을 지정해주면 array에 (속성1,속성2,...속성n)의 데이터 타입을 저장할 수 있다.

여기에

distances['id']
#array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

이렇게 dictionary처럼 속성명으로 속성값을 numpy array로 불러올수도 있고

distances['id'] = np.array([range(10)])
#array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

이렇게 대입해줄 수도 있다.

또한 원래 데이터가 일반 numpy 배열이라도 저런식으로 구조화되어 있는 데이터라면

student = np.array([['John',10],['Jane',12]])
#array([['John', '10'],
#       ['Jane', '12']], dtype='<U11')

s_student = np.core.records.fromarrays(student.transpose(), names='name, age', formats='S10, i4')
#rec.array([(b'John', 10), (b'Jane', 12)],
#          dtype=[('name', 'S10'), ('age', '<i4')])

이렇게 fromarrays를 사용하여 sturctured array로 바꿔줄 수 있다.

 

여기서 사용되는 data type는

(바이트배열순서-생략가능) + data type + data size

의 구조를 가지는데 여기서 바이트배열순서는 생략 가능이고 little endien이니 big endien이니 복잡하니 패스. 궁금하면 따로 찾아보시길

data type은

? = boolean

i = signed integer

f = float

U = unicode

S = String

O = object

정도만 알아두면 충분할듯

ex i4(int 4byte) f8(float 8byte) U10(10byte unicode 문자열)