NumPy 활용한 데이터 분석 입문(2) - 데이터 타입, reshape

천호영·2021년 6월 19일
0

Numpy의 데이터 타입

NumPy는 다양한 값을 저장 및 표현할 수 있는 다양한 데이터 타입을 제공합니다.
파이썬에서 제공하는 데이터 타입과 호환되며, 대표적인 데이터 타입은 다음과 같습니다.

np.int64 : (64비트) 정수
np.float64 : (64비트) 실수
np.complex : 복소수
np.bool : 불리언 (True, False)
np.object : 파이썬 객체
np.str : 문자열

ndarray.astype(dtype)
  • ndarray 에 저장된 데이터를 주어진 dtype 으로 변환해서 반환하는 함수
  • Parameters
    dtype : 변경하고자 하는 배열의 데이터 타입
  • 이때, 실제 값이 변환되는 것이 아니라 출력 값의 타입과 연산이 변환합니다.

<실습코드>

import numpy as np

'''
dtype 인자 지정을 통한 데이터 타입 변경
'''
data = [1, 2, 3]
cpx_arr = np.array(data, dtype=np.complex)
str_arr = np.array(data, dtype=np.str)
print(cpx_arr)
print(str_arr)

'''
샘플 데이터 생성
'''
origin = np.arange(1, 2, 0.2)
print('\nOriginal data')
print(origin)
print('dtype : ', origin.dtype)

'''
astype(dtype) 을 활용한 데이터 타입 변경
'''
result = origin.astype(int)
print('\nResult of astype(int)')
print(result)

print('\nOriginal data')
print(origin)

<실행결과>

[1.+0.j 2.+0.j 3.+0.j]
['1' '2' '3']

Original data
[1.  1.2 1.4 1.6 1.8]
dtype :  float64

Result of astype(int)
[1 1 1 1 1]

Original data
[1.  1.2 1.4 1.6 1.8]

Ndarray의 reshape

Ndarray의 shape을 변경하는 일은 빈번하게 발생합니다.
shape을 바꾸는 다양한 사례를 보고 자주 사용되는 reshape 함수에 대해 알아봅니다.

사례1) 이미지 데이터를 딥러닝에 적용 시, 2차원을 1차원의 형태로 펴줘야 합니다.
사례2) 머신러닝 알고리즘 적용을 위해 특정 독립변수 칼럼을 선택하여 1차원을 2차원으로 변경하기도 합니다. (10,)->(10,1)

np.reshape(array, newshape)
  • 기존 데이터는 유지하면서 차원과 shape 만을 바꾼 배열을 반환
  • Parameter
    array : reshape 할 ndarray
    newshape : 변경하고자 하는 shape 값(튜플 형태)
  • 호출방식 (결과는 동일)
    np.reshape(array, newshape)
    array.reshape(newshape)
  • reshape할 배열에 저장된 모든 데이터의 손실이 없도록 reshape 전/후의 배열의 size는 동일해야 합니다.
reshape(-1, N)
  • 기존 데이터를 유지하면서, shape 을 변경하는 방식
  • shape 은 주어진 N 에 따라 자동으로 추정되어 변경됨
  • -1 의 자리는 가변적이 됨

<실습코드>

import numpy as np

# ndarray 속성 출력 함수
def printinfo(arr):
  print(arr)
  print("shape: {}, size: {}, dtype: {}, dimension: {}"
        .format(arr.shape, arr.size, arr.dtype, arr.ndim))
        
# 샘플 데이터 생성
origin_arr = np.arange(15)
print('\nOriginal ndarray')
printinfo(origin_arr)

'''
reshape() 을 활용한 데이터 형상 변경
'''
reshape_arr = np.reshape(origin_arr, (3,5))
print('\nReshape ndarray')
printinfo(reshape_arr)

'''
origin_arr에 저장된 1차원 배열을 -1을 활용하여 2차원으로 형상 변경
'''
reshape_arr = reshape_arr.reshape(-1,1)
print('\nReshape(-1, N) to 2D array')
printinfo(reshape_arr)

<실행결과>

Original ndarray
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]
shape: (15,), size: 15, dtype: int64, dimension: 1

Reshape ndarray
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
shape: (3, 5), size: 15, dtype: int64, dimension: 2

Reshape(-1, N) to 2D array
[[ 0]
 [ 1]
 [ 2]
 [ 3]
 [ 4]
 [ 5]
 [ 6]
 [ 7]
 [ 8]
 [ 9]
 [10]
 [11]
 [12]
 [13]
 [14]]
shape: (15, 1), size: 15, dtype: int64, dimension: 2

0개의 댓글