본문 바로가기
Language/python

[numpy] numpy 소수점 반올림하기 / array 전체 출력 / 출력 형식 변경

by _YUJIN_ 2023. 1. 25.

반올림을 하거나 소수점 제한을 줘서 출력할 때, numpy에 있는 np.set_printoptions라는 메소드라는 것을 사용하면 된다.

jupyter로 작업을 할 경우, 상단의 셀에서 한번만 설정해주면 해당 파일의 작업들 전체에 설정을 따르게 된다.

 

소수점 반올림하기(precision)

* default = 8

np.array([0.123456789])

array([0.12345679])

 

np.set_printoptions(precision=5)
np.array([0.123456789])

array([0.12346])

 

np.set_printoptions(precision=8)
np.array([0.123456789])

array([0.12345679])

 

array 전체 출력(threshold)

* default = 1000

np.arange(50)

array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
       34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49])

 

#- 전체 출력 길이가 40개 이상이면 중간에 생략되서 ...으로 출력 됨
np.set_printoptions(threshold=40)
np.arange(50)

array([ 0, 1, 2, ..., 47, 48, 49])

 

#- 전체 출력 길이가 100개 이상이면 중간에 생략되서 ...으로 출력 됨
#- 해당 코드의 결과는 전체 출력 (출력 길이가 100개 이하이기 때문)
np.set_printoptions(threshold=100)
np.arange(50)

array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
       34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49])

 

#- 조건 없이 무조건 전체 출력할 경우
np.set_printoptions(threshold=np.inf)

 

출력 형식 만들기(formatter)

주의 ) 타입을 바꾸는게 아니라 출력형식을 바꾸는 방법!

< 설정 값 >

  • 'bool’
  • ‘int’
  • ‘timedelta’ 
  • ‘datetime’ 
  • ‘float’
  • ‘longfloat’ : 128-bit floats
  • ‘complexfloat’
  • ‘longcomplexfloat’ : composed of two 128-bit floats
  • ‘numpystr’ : types numpy.string_ and numpy.unicode_
  • ‘object’ : np.object_ arrays
  • ‘all’ : sets all types
  • ‘int_kind’ : sets ‘int’
  • ‘float_kind’ : sets ‘float’ and ‘longfloat’
  • ‘complex_kind’ : sets ‘complexfloat’ and ‘longcomplexfloat’
  • ‘str_kind’ : sets ‘numpystr’
np.set_printoptions(formatter={설정값:lambda x : 출력형식})


다시 원래대로 돌아오고 싶다면 , 아래 코드 실행

np.set_printoptions()
반응형