일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 나이브베이즈
- ML
- Naive Bayes
- python control statement
- 판다스
- 넘파이
- 머신러닝
- python
- KMeans Clustering
- 파이썬
- 파이썬 크롤러
- sklearn
- 파이썬 제어문
- NumPy
- 배열
- 순회 크롤러
- Machine Learning
- dataframe
- 파이썬 크롤링
- Python crawler
- pandas
- 파이썬 객체 지향 프로그래밍
- control statement
- 사이킷런
- scikit-learn
- Data pre-processing
- 타이타닉 데이터
- Titanic data set
- K평균군집화
- 제어문
- Today
- Total
Try to 개발자 EthanJ의 성장 로그
Basic Numpy 넘파이 기초 본문
Basic Numpy 넘파이 기초¶
NumPy (Numeriacal Python)¶
- Python Machine learning package
scikit-learn
>numpy
제공 배열 classnumpy.ndarray
instance를 기본 Data structure로 사용
- Python 기반 Data Analysis environment
> 행렬(matrix), 벡터(vector) operation에 필요한 다양한 method 제공
- Memory usage가 많은 loop문 사용 없이,
전체 data array에 빠른 연산을 처리할 수 있는 표준 수학 function
- 배열(array)
동일한 특성(data type) 및 일정한 규칙을 가지는 여러개의 요소(items)가 나열되어 있는 Data structure
- Python list object를 사용할 때 보다, Numpy의
ndarray
객체 사용 시
연산 속도 개선 > 더 많은 data를 더 빠른 속도로 처리 가능
import numpy as np
np.__version__
'1.21.5'
0. Numpy 배열 : numpy.ndarray
¶
> 다차원 배열(1차원, 2차원, 3차원, ..., n차원), 입체적인 데이터 구조를 구성, 여러 개의 데이터 방향을 가짐
배열 속성:
shape
,ndim
,dtype
등데이터 방향, 차원, 축의 추상화:
axis
> axis가 낮을수록 높은 차원, 새로운 축
if, ndim=3
, $0 \leq axis \leq 2$라면,
axis=0
: 면의 축 방향, page(depth) 단위axis=1
: 행의 축 방향, $\downarrow$, row 단위axis=2
: 열의 축 방향, $\rightarrow$, column 단위> shape=
(axis=0, axis=1, axis=2)
ndim=n
shape
=(n
차원,n-1
차원, ...,2
차원,1
차원)
=(axis=0
,axis=1
, ...,axis=n-2
,axis=n-1
)
1. ndarray
배열 생성¶
: np.array(data)
> Python list obj를 전달받아 > numpy 배열 ndarray
로 return
배열 속성
arr.shape
: structure (n
차원,n-1
차원, ...,2
차원,1
차원)
\=(axis=0
,axis=1
, ...,axis=n-2
,axis=n-1
)arr.ndim
: N dimensionsarr.dtype
: item data type > must be standaradaizedarr.size
: item 개수 (== n depths n rows n columns > n*n*n))
배열 method
arr.astype(type)
: item dtype 변환 (str > float, int > str 등 ...)
Python method
type(arr)
: arr의 data type :<class 'numpy.ndarray'>
len(arr)
: if shape=(a, b, c, ...) > arr의 가장 큰 dimension의 item 수 == a
Numpy method
arr.reshape(row, column)
: 배열 구조shape
재배치 :1 X 12 > 3 X 4, 4 X 5 > 2 X 10 등 ...)
kind
: item dtype에 대한 구분 기호b
: booleani
: 정수(int)u
: unsigned int, $\pm$ 개념 없이 절대값만 존재f
: 실수(float)c
: 복소 부동소수점O
: 객체(Object)S
: byte 문자열(ASCII code, 영문자, 일부 특수문자, 숫자)U
: UNICODE 문자열(한글, 태국어, 아랍어 등 영문자 제외 문자)
- Python 1차원 list > Numpy
ndarry
로 변환
tmp_list = [1, 2, 3, 4, 5, 6]
my_arr = np.array(tmp_list)
my_arr
array([1, 2, 3, 4, 5, 6])
print(type(tmp_list))
print(type(my_arr))
<class 'list'> <class 'numpy.ndarray'>
- 구조:
arr.shape
>tuple(n-1차원, n차원, ..., 1차원, 0차원)
print(my_arr.shape)
(6,)
- 길이:
len(arr)
> shape tuple의 첫 번째 item
len(my_arr)
6
- 차원:
arr.ndim
:ndim=n
> shape=(n
차원,n-1
차원, ...,2
차원,1
차원)
my_arr.ndim
1
- data item 개수:
arr.size
print(my_arr.size)
arr_2d = np.arange(0, 12).reshape(3, 4)
print(arr_2d.size)
6 12
- item data type:
ndarray.dtype
my_arr.dtype
dtype('int32')
- item data type 변환:
arr.astype(type)
> 원본 arr data 유지
my_arr2 = my_arr.astype(float)
my_arr2.dtype
dtype('float64')
- 배열 구조 변환
ndarray.reshape(row, col)
> 기존 배열 shape item수와 변환하려는 shape item수는 일치해야 함
my_arr3 = my_arr.reshape(2, 3)
print(my_arr3)
print(my_arr)
[[1 2 3] [4 5 6]] [1 2 3 4 5 6]
- 함수
np_print()
할당: numpy objectndarray
정보 확인 function
>obj type, shape, dim, dtype, obj data
확인
def np_print(arr):
print(f"""
type : {type(arr)}
shape : {arr.shape}
ndim : {arr.ndim}
dtype : {arr.dtype}
array data : \n {arr}""")
1.2. 배열 객체 ndarray
dtype standardize¶
list item dtype이 standardized 되지 않으면, list가
ndarray
로 변환 될 때,
우선순위에 따라 item의 dtype이 통일된다우선순위: str > float > int
- int + str > str
int_str = [1, 2, 3, '4']
mixed_arr1 = np.array(int_str)
np_print(mixed_arr1)
type : <class 'numpy.ndarray'> shape : (4,) ndim : 1 dtype : <U11 array data : ['1' '2' '3' '4']
- int + float > float
int_float = [1, 2, 3.3, 4]
mixed_arr2 = np.array(int_float)
np_print(mixed_arr2)
type : <class 'numpy.ndarray'> shape : (4,) ndim : 1 dtype : float64 array data : [1. 2. 3.3 4. ]
- float + str > str
float_str = ['1', 2.3, 4]
mixed_arr3 = np.array(float_str)
np_print(mixed_arr3)
type : <class 'numpy.ndarray'> shape : (3,) ndim : 1 dtype : <U32 array data : ['1' '2.3' '4']
1.3. n차원 리스트로 배열 생성¶
- 2차원 list >
ndarray
생성
- 2차원 배열: shape=(행(row, 세로축 기준 개수), 열(column, 가로축 기준 개수))
>shape=(row,column)
두 개만 item으로 가짐
tmp_list = [[1, 2, 3, 4],
[5, 6, 7, 8]]
arr_2d = np.array(tmp_list)
np_print(arr_2d)
print(arr_2d[1][1])
type : <class 'numpy.ndarray'> shape : (2, 4) ndim : 2 dtype : int32 array data : [[1 2 3 4] [5 6 7 8]] 6
- 3차원 list로
ndarray
생성
tmp_list = [
[
[1, 2, 3], [4, 5, 6]
]
]
arr_3d = np.array(tmp_list)
np_print(arr_3d)
print(arr_3d[0][1][2])
type : <class 'numpy.ndarray'> shape : (1, 2, 3) ndim : 3 dtype : int32 array data : [[[1 2 3] [4 5 6]]] 6
1.5. dtype 지정 ndarray
생성¶
np.array(data, dtype=data_type)
>dtype
을 optional parameter로 지정 > 배열dtype
지정 생성 가능
float_3d = np.array(tmp_list, dtype=float)
np_print(float_3d)
type : <class 'numpy.ndarray'> shape : (1, 2, 3) ndim : 3 dtype : float64 array data : [[[1. 2. 3.] [4. 5. 6.]]]
2. 데이터 초기화와 함께 ndarray
생성 method¶
초기값을 지정하여 data를 자동으로 가지는
ndarray
생성np.zeros(shape)
np.ones(shape)
np.full(shape, fill_value)
np.eye(N)
np.empty(shape)
2.1. np.zeros(shape, dtype=float)
¶
지정된 구조
shape
의 배열을 생성하고 모든 items를 value=0
으로 초기화shape
: tuple type,(row, col)
지정dtype
: 배열의 item data type 지정, default:dtype=numpy.float64
- shape=
(3, 4)
zeros_3_4 = np.zeros((3, 4))
np_print(zeros_3_4)
type : <class 'numpy.ndarray'> shape : (3, 4) ndim : 2 dtype : float64 array data : [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]]
dtype=int
zeros_int = np.zeros((3, 4), dtype=int)
np_print(zeros_int)
type : <class 'numpy.ndarray'> shape : (3, 4) ndim : 2 dtype : int32 array data : [[0 0 0 0] [0 0 0 0] [0 0 0 0]]
2.2. np.ones(shape, dtype=float)
¶
지정된 구조
shape
의 배열을 생성하고 모든 items를 value=1
으로 초기화shape
: tuple type,(row, col)
지정dtype
: 배열의 item data type 지정, default:dtype=numpy.float64
- row 3 X column 4, 초기값 1로 가지는 배열
arr_ones = np.ones((3, 4))
np_print(arr_ones)
type : <class 'numpy.ndarray'> shape : (3, 4) ndim : 2 dtype : float64 array data : [[1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]]
2.3. np.full(shape, fill_value, dtype=None)
¶
지정된 구조
shape
의 배열을 생성하고 모든 items를 value=fill_value
으로 초기화shape
: tuple type,(row, col)
지정dtype
: 배열의 item data type 지정, default:dtype=None
==np.array(fill_value).dtype
- 3행 4열 초기값 5인 배열
arr_full = np.full((3, 4), 5, int)
np_print(arr_full)
type : <class 'numpy.ndarray'> shape : (3, 4) ndim : 2 dtype : int32 array data : [[5 5 5 5] [5 5 5 5] [5 5 5 5]]
2.4. np.eye(N, M=None, dtype=float)
¶
shape=(N, M)
의 단위 행렬 생성 (N행 X M열)단위 행렬: 주대각 성분만 값을 가지고, 그 값이
1
인 행렬M
: column 개수 지정, default:M=None
==N
dtype
: 배열의 item data type 지정, default:dtype=numpy.float64
ndarr_eye = np.eye(3)
np_print(ndarr_eye)
type : <class 'numpy.ndarray'> shape : (3, 3) ndim : 2 dtype : float64 array data : [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]
N=5, M=3
인 단위행렬 (5행 3열)
eye_5_3 = np.eye(5, 3)
np_print(eye_5_3)
type : <class 'numpy.ndarray'> shape : (5, 3) ndim : 2 dtype : float64 array data : [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.] [0. 0. 0.] [0. 0. 0.]]
2.5. np.empty(shape, dtype=float)
¶
지정된 구조
shape
의 배열을 생성하고, 모든 items의 value를직전 memory에 저장된 values
로 초기화ndarry
생성 시 가장 빠르고 효율적인 방법shape
: tuple type,(row, col)
지정dtype
:ndarray
의 data type 지정, default:dtype=numpy.float64
- 6 X 2, 1이상 12이하 data를 가진 배열 생성
data_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
origin_arr = np.array(data_list).reshape(6, 2)
np_print(origin_arr)
type : <class 'numpy.ndarray'> shape : (6, 2) ndim : 2 dtype : int32 array data : [[ 1 2] [ 3 4] [ 5 6] [ 7 8] [ 9 10] [11 12]]
- row 3 X column 4 구조의 직전 memory에 사용된 값을 갖는 배열 생성
arr_empty = np.empty((3, 4), dtype=int)
np_print(arr_empty)
type : <class 'numpy.ndarray'> shape : (3, 4) ndim : 2 dtype : int32 array data : [[0 0 0 0] [0 0 0 0] [0 0 0 0]]
2.6. np.sth_like(arr)
method¶
- 전달받은
arr
과 동일한 shape으로 > 새로운 초기값 갖는ndarry
returned
np.zeros_like(arr)
: 초기값 ==0
np.ones_like(arr)
: 초기값 ==1
np.full_like(arr)
: 초기값 ==fill_vaule
shape=(2, 3)
구조, 1 이상 6 이하 값으로 구성된 배열
data_list = [[1, 2, 3], [4, 5, 6]]
origin_arr = np.array(data_list)
np_print(origin_arr)
type : <class 'numpy.ndarray'> shape : (2, 3) ndim : 2 dtype : int32 array data : [[1 2 3] [4 5 6]]
- 동일한
shape=(2, 3)
으로 value=0
인 배열
ones_like_arr = np.ones_like(origin_arr)
np_print(ones_like_arr)
type : <class 'numpy.ndarray'> shape : (2, 3) ndim : 2 dtype : int32 array data : [[1 1 1] [1 1 1]]
3. 범위, 조건 있는 1차원 배열 생성 및 초기화 method¶
np.linspace(start, stop)
np.arange(stop)
np.logspace(start, stop)
3.1. np.linspace(start, stop)
¶
np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
- 시작값
start
이상 마지막값stop
이하의 범위 > 균등한 간격으로 일정 개수num
개의 data를 가지는 배열 생성
num
: 데이터 개수, default:num=50
endpoint
: 배열에 stop값을 포함 or 제외 조건 지정, default:endpoint=True
> 포함retstep
: True > return(ndarray, gap_value_between_datas)
tuple, defalut:retstep=False
(returnndarray
)dtype
: 배열의 item data type을 지정, default:dtype=None
- 0이상 1이하의 범위에서 숫자 5개를 포함하는 배열
arr_linspace = np.linspace(0, 1, num=5)
np_print(arr_linspace)
type : <class 'numpy.ndarray'> shape : (5,) ndim : 1 dtype : float64 array data : [0. 0.25 0.5 0.75 1. ]
endpoint=False
linspace_ep_False = np.linspace(0, 10, endpoint=False)
np_print(linspace_ep_False)
type : <class 'numpy.ndarray'> shape : (50,) ndim : 1 dtype : float64 array data : [0. 0.2 0.4 0.6 0.8 1. 1.2 1.4 1.6 1.8 2. 2.2 2.4 2.6 2.8 3. 3.2 3.4 3.6 3.8 4. 4.2 4.4 4.6 4.8 5. 5.2 5.4 5.6 5.8 6. 6.2 6.4 6.6 6.8 7. 7.2 7.4 7.6 7.8 8. 8.2 8.4 8.6 8.8 9. 9.2 9.4 9.6 9.8]
retstep=True
> return(ndarray, gap_value)
tuple
linspace_retstep = np.linspace(0, 10, num=9, retstep=True)
print(linspace_retstep)
(array([ 0. , 1.25, 2.5 , 3.75, 5. , 6.25, 7.5 , 8.75, 10. ]), 1.25)
3.2. np.arange(stop)
¶
np.arange(start=0, stop, step=1, dtype=None)
- 시작값
start
이상 최대한도값stop
미만 범위, 지정한 간격step
으로 일정 개수num
개의 data를 가지는 배열 생성
start
: 시작값, default:start=0
stop
: 최대한도값, not included > like Python methodrange()
step
: gap between datas, default:step=1
dtype
: 배열의 item dtype을 지정, default:dtype=None
list(range(5))
[0, 1, 2, 3, 4]
- 0 이상 5 미만 범위, 1씩 증가하는 int data가진
ndarray
생성
arr_arange = np.arange(5)
np_print(arr_arange)
type : <class 'numpy.ndarray'> shape : (5,) ndim : 1 dtype : int32 array data : [0 1 2 3 4]
start
,stop
,step
설정- 0 이상, 5 미만, 0.5씩 증가하는 float data를 가진
ndarray
arange_half = np.arange(start=0, stop=5, step=0.5)
np_print(arange_half)
type : <class 'numpy.ndarray'> shape : (10,) ndim : 1 dtype : float64 array data : [0. 0.5 1. 1.5 2. 2.5 3. 3.5 4. 4.5]
ndarray
assigned by >np.arange(1, 5)
method vs.arr.reshape(1, 4)
method
: differs inshape
andndim
aran_arr = np.arange(1, 5)
tmp_list = [1, 2, 3, 4]
my_arr = np.array(tmp_list)
re_arr = my_arr.reshape(1, 4)
np_print(aran_arr)
np_print(re_arr)
type : <class 'numpy.ndarray'> shape : (4,) ndim : 1 dtype : int32 array data : [1 2 3 4] type : <class 'numpy.ndarray'> shape : (1, 4) ndim : 2 dtype : int32 array data : [[1 2 3 4]]
3.3. np.logspace(start, stop)
¶
np.logspace(start, stop, num=50, endpoint=True, dtype=None)
- 시작값
start
부터 마지막값stop
사이의 log scale로 지정된 range > 균일 간격, 일정 개수num
의 data를 가지는 배열 생성
num
: data 개수, default:num=50
endpoint
: valuestop
whether included or excluded, default:endpoint=True
> includeddtype
: arr item dtype, default:dtype=None
0이상 1이하 range, log scale 적용, 50개 data를 가진
ndarray
밑 == 10 log값 > 0이상 1이하일 때의 진수값
arr_logspace = np.logspace(0, 1)
np_print(arr_logspace)
type : <class 'numpy.ndarray'> shape : (50,) ndim : 1 dtype : float64 array data : [ 1. 1.04811313 1.09854114 1.1513954 1.20679264 1.26485522 1.32571137 1.38949549 1.45634848 1.52641797 1.59985872 1.67683294 1.75751062 1.84206997 1.93069773 2.02358965 2.12095089 2.22299648 2.32995181 2.44205309 2.55954792 2.6826958 2.8117687 2.9470517 3.0888436 3.23745754 3.39322177 3.55648031 3.72759372 3.90693994 4.09491506 4.29193426 4.49843267 4.71486636 4.94171336 5.17947468 5.42867544 5.68986603 5.96362332 6.25055193 6.55128557 6.86648845 7.19685673 7.54312006 7.90604321 8.28642773 8.68511374 9.10298178 9.54095476 10. ]
start=0
,stop=3
,num=4
> 상용로그값이 0 ~ 3일 때의 진수값
arr_logspace2 = np.logspace(0, 3, num=4)
np_print(arr_logspace2)
type : <class 'numpy.ndarray'> shape : (4,) ndim : 1 dtype : float64 array data : [ 1. 10. 100. 1000.]
endpoint=False
logspace_ep_False = np.logspace(0, 1, num=20, endpoint=False)
np_print(logspace_ep_False)
type : <class 'numpy.ndarray'> shape : (20,) ndim : 1 dtype : float64 array data : [1. 1.12201845 1.25892541 1.41253754 1.58489319 1.77827941 1.99526231 2.23872114 2.51188643 2.81838293 3.16227766 3.54813389 3.98107171 4.46683592 5.01187234 5.62341325 6.30957344 7.07945784 7.94328235 8.91250938]
4. 난수 배열 생성 및 초기화¶
난수(특정한 순서나 규칙을 가지지 않는 무작위의 수)를 data로 가지는
ndarray
를 생성np.random.normal()
np.random.rand()
np.random.randn()
np.random.randint()
np.random.random()
4.1. np.random.normal(loc=0.0, scale=1.0, size=None)
¶
- 정규분포 확률밀도함수에서 추출된 표본을 data로 가지는 배열을 생성
loc
(location parameter): 정규분포의 평균, default:loc=0.0
scale
(scale parameter): 정규분포의 표준편차, default:scale=1.0
size
: shape=(shape)
,type=iterator
, default:size=None
> single value(하나의 값)
분포의 종류¶
균등분포 : 모든 요소가 출력될 확률이 동등한 경우 e.g. 로또 번호
정규분포 : 평균에 가까울수록 출력될 확률이 높고 평균에서 멀어질수록 확률이 낮아짐 e.g. 키, 시험 성적
- 평균 0, 표준편차 1로 난수 생성
rand_normal = np.random.normal(0, 1)
print(rand_normal)
-0.3837880170014499
분산과 표준편차¶
(집단간 평균이 같다) != (집단간 분포가 같다)
분산: 평균에서 각 요소가 얼마나 멀리 떨어져 있는지 나타내는 값, 척도
- 분산의 제곱근 $\sigma$ = 표준편차 > 분포 확인 가능 > 상대평가 가능
size=(axis=0, axis=1, axis=3, ..., axis=n)
rand_normal_2dim = np.random.normal(size=(3, 4))
rand_normal_3dim = np.random.normal(size=(2, 3, 4))
np_print(rand_normal_2dim)
np_print(rand_normal_3dim)
type : <class 'numpy.ndarray'> shape : (3, 4) ndim : 2 dtype : float64 array data : [[ 0.16772998 0.64882207 -2.08712314 0.66190438] [-0.36548969 -0.51442573 0.56566425 1.07290755] [-0.79453076 -1.78283196 -0.15843509 -0.82587582]] type : <class 'numpy.ndarray'> shape : (2, 3, 4) ndim : 3 dtype : float64 array data : [[[ 0.41825561 -1.30721298 0.59147123 -2.0999777 ] [ 0.00346312 -0.40829265 -0.23860304 0.52634703] [ 2.77750745 0.46155579 -0.78902921 -0.37957547]] [[-0.39731518 -0.3340476 -0.76015944 1.16243451] [ 1.79063945 0.37615559 -0.09850383 0.2357968 ] [-1.18722942 -0.90941277 0.60274449 -0.01414508]]]
정규분포 확률밀도함수에서 추출된 data로 이루어진 배열에 대한 시각화
$\bar{x}=10, \sigma^2=2$, 정규분포에서 추출한 10000개의 data
rand_normal_arr = np.random.normal(10, 2, 10000)
rand_normal_arr
array([10.39662886, 13.75015286, 11.8128948 , ..., 6.91198848, 13.13682259, 10.57447306])
- $\bar{x}\pm(\sigma^2\times 1)$ > 8 ~ 12 > 약 68%
- $\bar{x}\pm(\sigma^2\times 1.96)$ > 6.08 ~ 13.92 > 약 95%
- 시각화 라이브러리
matplotlib.pyplot
import matplotlib.pyplot as plt
bins=n
: 구간의 개수 n
> bins=n
up > 막대 폭 down100개 구간으로 구분한 분포
plt.hist(rand_normal_arr, bins=100)
plt.show
<function matplotlib.pyplot.show(close=None, block=None)>
4.2. np.random.rand(d0, d1, d2, ... , dn)
¶
지정 shape
(d0, d1, d2, ... , dn)
에 따라ndarray
를 생성 > 난수로 초기화사용되는 난수: 0 이상 1 미만 , 균등 분포로 추출
d0=2
,d1=3
> 2 rows X 3 columns shape
rand_rand_arr = np.random.rand(2, 3)
np_print(rand_rand_arr)
type : <class 'numpy.ndarray'> shape : (2, 3) ndim : 2 dtype : float64 array data : [[0.36004065 0.06552129 0.55500004] [0.69662426 0.74952219 0.0602567 ]]
- 1000개의 균등분포 data
ndarray
> 100개 구간으로 구분한 분포 시각화
rand_rand_thou = np.random.rand(1000)
plt.hist(rand_rand_thou, bins=10)
plt.show
<function matplotlib.pyplot.show(close=None, block=None)>
numpy.ndarray
: 곱연산*
> 반복 연장 X, 각 item data에 scarla 곱연산
np.array([1, 2, 3, 4]) * 10
array([10, 20, 30, 40])
4.3. np.random.randn(d0, d1, d2, ..., dn)
¶
지정 shape
(d0, d1, d2, ..., dn)
에 따라 배열 생성, 난수로 초기화사용되는 난수: 표준정규분포에서 추출된 data
rand_randn_2dim = np.random.randn(3, 4)
np_print(rand_randn_2dim)
type : <class 'numpy.ndarray'> shape : (3, 4) ndim : 2 dtype : float64 array data : [[ 0.63336975 -0.19236503 -0.01897049 1.22904304] [ 0.69965311 0.45555254 1.07375112 -1.07568909] [ 0.79130969 1.9800219 0.04745383 -0.46390351]]
- $\bar{x}=0, \sigma^2=1$, 표준정규분포에서 추출한 1000개의 정규분포 data, 100개의 구간
rand_randn_data = np.random.randn(1000)
plt.hist(rand_randn_data, bins=100)
plt.show
<function matplotlib.pyplot.show(close=None, block=None)>
4.4. np.random.randint(low)
¶
np.random.randint(low, high=None, size=None, dtype=I)
low
이상,high
미만, int로 구성된 data >size
의 배열 생성
low
:high
값이 지정되지 않으면,low
값이 최대값(포함X)로 설정high
: 최대값(포함X), default:high=None
size
: 배열의 구조, default:size=None
> 배열이 아닌 하나의 값(single value) 반환
1 미만의 값 한 개 추출
size
미지정: default:size=None
> shape 미지정 > return single value
rand_randint_value = np.random.randint(1)
print(rand_randint_value)
0
- 0 이상 3 미만 정수 10개 추출
rand_randint_ten = np.random.randint(0, 3, size=(10))
np_print(rand_randint_ten)
type : <class 'numpy.ndarray'> shape : (10,) ndim : 1 dtype : int32 array data : [1 0 0 2 0 1 0 0 2 2]
- 3 초과 10 미만 정수,
size=(2, 4)
> 2 rows X 4 columns 배열로 추출
rand_randint_arr = np.random.randint(4, 10, size=(2, 4))
np_print(rand_randint_arr)
type : <class 'numpy.ndarray'> shape : (2, 4) ndim : 2 dtype : int32 array data : [[8 6 7 8] [9 7 7 6]]
- -100 이상 +100 미만 정수 범위, 10000개 균등분포 data, 25개 구간 시각화
rand_randint_data = np.random.randint(-100, 100, size=10000)
plt.hist(rand_randint_data, bins=24)
plt.show
<function matplotlib.pyplot.show(close=None, block=None)>
rand_random_value = np.random.random()
print(rand_random_value)
0.40292291967725735
- 0이상 1미만의 실수 data 1000개 추출, 10구간으로 분포, 시각화
rand_random_data = np.random.random(size=1000)
plt.hist(rand_random_data, bins=10)
plt.show
<function matplotlib.pyplot.show(close=None, block=None)>
5. 난수: 무작위의 숫자¶
programming에서 추출되는 난수: 무작위로 만들어진 것 처럼 보이지만
실제로는 고정된 기준(시작점)을 가지고 규칙적으로 생성고정된 기준(시작점)을 설정 > 동일한 난수 생성 가능
난수의 시작점 설정 method:
np.random.seed()
np.random.seed(100)
- 0이상 1미만 지정범위에서 실수값을 가지는 3행 X 3열 난수 배열 생성
rand_random_arr = np.random.random(size=(3, 3))
np_print(rand_random_arr)
type : <class 'numpy.ndarray'> shape : (3, 3) ndim : 2 dtype : float64 array data : [[0.54340494 0.27836939 0.42451759] [0.84477613 0.00471886 0.12156912] [0.67074908 0.82585276 0.13670659]]
- 0 이상 5 미만의 지정범위에서 정수값을 가지는 2행 X 2열 난수 배열 생성
rand_randint_arr = np.random.randint(0, 5, size=(2, 2))
np_print(rand_randint_arr)
type : <class 'numpy.ndarray'> shape : (2, 2) ndim : 2 dtype : int32 array data : [[0 4] [3 4]]
np.random.seed()
np_print(np.random.random(size=(3, 3)))
np_print(np.random.randint(0, 5, size=(2, 2)))
type : <class 'numpy.ndarray'> shape : (3, 3) ndim : 2 dtype : float64 array data : [[0.57471428 0.62015475 0.08872435] [0.30270601 0.67077139 0.96129412] [0.7733534 0.57351219 0.07505024]] type : <class 'numpy.ndarray'> shape : (2, 2) ndim : 2 dtype : int32 array data : [[4 4] [2 1]]
'CS & DS > Numpy & Pandas' 카테고리의 다른 글
Pandas Data Loading 판다스 데이터 적재 (0) | 2022.11.05 |
---|---|
Pandas DataFrame 판다스 데이터프레임 (0) | 2022.11.05 |
Pandas Series 판다스 시리즈 (0) | 2022.11.03 |
Numpy array Manipulation 넘파이 배열 변형 (0) | 2022.11.02 |
Numpy Operation 넘파이 연산 (0) | 2022.10.30 |