NumPy 기본 사용법

2024. 7. 29. 21:33프로그래밍 (확장)/Python-NumPy

NumPy

NumPy 가져오기

import numpy as np

 

배열 생성


# 리스트로부터 생성

arr = np.array([1, 2, 3, 4, 5])

# 튜플로부터 생성

arr = np.array((1, 2, 3, 4, 5))

# 0으로 채워진 배열 생성

arr = np.zeros((2, 3)) # 2x3 배열

# 1로 채워진 배열 생성

arr = np.ones((2, 3)) # 2x3 배열

# 일정 범위의 값을 가지는 배열 생성

arr = np.arange(0, 10, 2) # 0부터 10까지 2씩 증가하는 배열

# 일정 간격으로 나눈 값을 가지는 배열 생성

arr = np.linspace(0, 1, 5) # 0부터 1까지 5개의 값을 가지는 배열

https://numpy.org/doc/stable/user/quickstart.html#creating-arrays

 

NumPy quickstart — NumPy v2.0 Manual

NumPy provides familiar mathematical functions such as sin, cos, and exp. In NumPy, these are called “universal functions” (ufunc). Within NumPy, these functions operate elementwise on an array, producing an array as output. See also all, any, apply_al

numpy.org

 

배열 정보 확인


arr.shape # 배열의 형태 반환  
arr.size # 배열의 요소 수 반환  
arr.ndim # 배열의 차원 수 반환  
arr.dtype # 배열의 데이터 타입 반환

https://numpy.org/doc/stable/reference/arrays.ndarray.html#attributes-of-array

 

The N-dimensional array (ndarray) — NumPy v2.0 Manual

The N-dimensional array (ndarray) An ndarray is a (usually fixed-size) multidimensional container of items of the same type and size. The number of dimensions and items in an array is defined by its shape, which is a tuple of N non-negative integers that s

numpy.org

 

배열 인덱싱 및 슬라이싱


# 인덱싱

arr[0] # 첫 번째 요소  
arr[-1] # 마지막 요소

# 슬라이싱

arr[1:3] # 인덱스 1부터 2까지의 요소  
arr[:3] # 처음 세 요소  
arr[::2] # 두 번째 요소마다

# 다차원 배열

arr2d = np.array([[1, 2, 3], [4, 5, 6]])  
arr2d[0, 0] # 첫 번째 행의 첫 번째 요소  
arr2d[0, :] # 첫 번째 행  
arr2d[:, 0] # 첫 번째 열

https://numpy.org/doc/stable/user/quickstart.html#indexing-slicing-and-iterating

 

NumPy quickstart — NumPy v2.0 Manual

NumPy provides familiar mathematical functions such as sin, cos, and exp. In NumPy, these are called “universal functions” (ufunc). Within NumPy, these functions operate elementwise on an array, producing an array as output. See also all, any, apply_al

numpy.org

 

배열 조작


# 형태 변경

arr = arr.reshape((3, 2)) # 3x2 배열로 형태 변경

# 전치

arr = arr.T # 배열 전치

# 평탄화

arr = arr.flatten() # 1차원 배열로 평탄화

# 배열 연결

arr1 = np.array([1, 2, 3])  
arr2 = np.array([4, 5, 6])  
arr = np.concatenate((arr1, arr2)) # 두 배열 연결

# 배열 쌓기

arr_v = np.vstack((arr1, arr2)) # 수직 쌓기  
arr_h = np.hstack((arr1, arr2)) # 수평 쌓기

https://numpy.org/doc/stable/reference/routines.array-manipulation.html

 

Array manipulation routines — NumPy v2.0 Manual

asarray(a[, dtype, order, device, copy, like]) Convert the input to an array.

numpy.org

 

수학 연산


# 요소별 연산

arr = np.array([1, 2, 3])  
arr + 1 # 각 요소에 1을 더함  
arr * 2 # 각 요소에 2를 곱함

# 유니버설 함수

np.sqrt(arr) # 각 요소의 제곱근  
np.exp(arr) # 각 요소의 지수  
np.sin(arr) # 각 요소의 사인  
np.log(arr) # 각 요소의 자연 로그

# 집계 함수

np.sum(arr) # 모든 요소의 합  
np.mean(arr) # 모든 요소의 평균  
np.max(arr) # 최대 요소  
np.min(arr) # 최소 요소  
np.std(arr) # 모든 요소의 표준 편차

https://numpy.org/doc/stable/reference/routines.math.html

 

Mathematical functions — NumPy v2.0 Manual

pow(x1, x2, /[, out, where, casting, order, ...]) First array elements raised to powers from second array, element-wise.

numpy.org

 

난수


# 난수 생성

np.random.rand(3, 2) # 0과 1 사이의 균일 분포 난수  
np.random.randn(3, 2) # 표준 정규 분포 난수  
np.random.randint(0, 10, (3, 2)) # 0부터 10 사이의 정수 난수

https://numpy.org/doc/stable/reference/random/index.html

 

Random sampling (numpy.random) — NumPy v2.0 Manual

The numpy.random module implements pseudo-random number generators (PRNGs or RNGs, for short) with the ability to draw samples from a variety of probability distributions. In general, users will create a Generator instance with default_rng and call the var

numpy.org

 

선형 대수


# 내적

arr1 = np.array([[1, 2], [3, 4]])  
arr2 = np.array([[5, 6], [7, 8]])  
np.dot(arr1, arr2) # 내적

# 행렬식

np.linalg.det(arr1) # 배열의 행렬식

# 역행렬

np.linalg.inv(arr1) # 배열의 역행렬

# 고유값 및 고유벡터

vals, vecs = np.linalg.eig(arr1) # 고유값과 고유벡터

https://numpy.org/doc/stable/reference/routines.linalg.html

 

Linear algebra (numpy.linalg) — NumPy v2.0 Manual

The NumPy linear algebra functions rely on BLAS and LAPACK to provide efficient low level implementations of standard linear algebra algorithms. Those libraries may be provided by NumPy itself using C versions of a subset of their reference implementations

numpy.org

 

 

NumPy 치트시트: https://www.kaggle.com/discussions/getting-started/255139

 

🔥 10 Best NumPy Cheat Sheets ✔️ | Kaggle

🔥 10 Best NumPy Cheat Sheets ✔️ .

www.kaggle.com