Python Numpy의 random
모듈은 난수 배열을 생성하는 모듈입니다.
N차원의 랜덤 숫자 배열을 생성할 수 있습니다. 예제와 함께 자세히 알아보겠습니다.
1차원의 난수 배열 생성 : random.rand()
rand(N)
은 길이가 N인 1차원 배열을 생성하며, 난수는 [0~1) 범위의 숫자가 됩니다.
import numpy as np
a = np.random.rand(3)
print(a)
Output:
[0.75212271 0.51562219 0.22850086]
2차원 난수 배열 생성 : random.rand()
rand(N, M)
은 NxM 크기의 난수 배열을 생성합니다.
import numpy as np
b = np.random.rand(2, 3)
print(b)
Output:
[[0.06739028 0.9726255 0.30878199]
[0.37131462 0.50416328 0.36436312]]
1차원 범위 난수 배열 생성 : random.randint()
randint(N, size=S)
는 크기가 S인 [0, N) 범위의 1차원 난수 배열을 생성randint(N, M, size=S)
는 크기가 S인 [N, M) 범위의 1차원 난수 배열을 생성
a = np.random.randint(3, size=5)
print(a)
b = np.random.randint(5, 10, size=5)
print(b)
Output:
[1 0 1 0 2]
[2 2 3 3 2]
2차원 범위 난수 배열 생성 : random.randint()
2차원 배열을 생성할 때는 size=(N, M)
처럼 배열 크기를 전달하면 됩니다. 숫자 범위 설정 방법은 위와 동일합니다.
import numpy as np
a = np.random.randint(3, size=(2, 3))
print(a)
b = np.random.randint(5, 10, size=(2, 3))
print(b)
Output:
[[0 2 2]
[2 0 0]]
[[7 9 9]
[5 6 6]]
random_sample()로 난수 배열 생성
random_sample()
은 난수 리턴random_sample((N, M))
은 NxM 난수 배열 리턴- 난수 범위는 [0, 1)
import numpy as np
a = np.random.random_sample()
print(a)
b = np.random.random_sample((2, 3))
print(b)
Output:
0.9353513751193463
[[0.64614507 0.22747339 0.01151063]
[0.27724488 0.11845794 0.22551394]]
Loading script...
Related Posts
- numpy.arange(), 균일 간격 배열
- numpy.concatenate(), 배열 합치기
- numpy hstack, vstack 함수 (배열 연결)
- numpy.average(), 배열 가중 평균
- Numpy 배열을 List로 변환
- 파이썬 List를 Numpy 배열로 변환
- numpy flatten() 함수, 1차원 배열로 변환(평탄화)
- numpy의 min(), max() 함수 (최소, 최대 값)
- numpy.mean(), 배열 평균 계산
- numpy.log(), 로그 함수 사용 방법
- numpy.shape(), 배열 크기/형태/차원 확인
- numpy.sqrt(), 배열의 제곱근 계산
- numpy.zeros(), 0으로 채워진 배열 생성
- Python Numpy 버전 확인 방법
- numpy.argsort(), 배열 정렬
- numpy.clip(), 배열의 최대/최소 값 지정
- numpy.linspace(), 동일 간격 숫자 배열
- Numpy - random 모듈, 난수 배열 생성
- Numpy의 ndarray 사용 방법 알아보기
- numpy.transpose(), 전치 행렬 변환
- Numpy - where() 사용 방법
- Python - numpy.append(), 배열 추가
- Python numpy.random.choice(), 랜덤 샘플링
- Python numpy.reshape(), 배열 차원 변경
- Python numpy.sum(), 배열의 합
- Python numpy.unique(), 배열 중복 제거
- Python - json.dumps()로 JSON 출력하기
- Python - find() 문자 위치 찾기
- Python lower() 문자열 소문자로 변환
- Python upper() 문자열 대문자로 변환
- Python 에러 해결, 'conda' 용어가 cmdlet, 함수, 스크립트 ... 인식되지 않습니다.
- Python 에러 해결, AttributeError: module 'jwt' has no attribute 'encode'
- Python - assert 사용 방법
- Python - Counter로 Collection 개수 세기
- Python - enumerate(), for/index 예제