[파이썬] Numpy 기초

2021. 7. 24. 02:37공부한 내용/파이썬 문법

1. NumPy 정의

-NumPy: 배열을 사용하여 효율적인 데이터 구조를 지원하는 파이썬 패키지

 

 

2. Metadata About The Array

① shape: A tuple that contains the number of elements for each dimension of the array

② size: The total number elements in the array

③ ndim: Number of dimensions (axes)

④ nbytes: Number of btyes used to store the data

⑤ dtype: The data type of the elements in the array

import numpy as np
data = np.array([[1,2],[3,4],[5,6]])

data.shape
#> (3, 2)

data.size
#> 6

data.ndim
#> 2

data.nbtyes
#> 24

data.dtype
#> dtype('int32')

 

 

3. Basic Numerical Data Types

① int: Integers

② uint: Unsigned (nonnegative) integers

③ bool: Boolean (True or False)

④ float: Floating-point numbers

⑤ complex: Complex-valued floating-point numbers

np.array([1, 2, 3], dtype=np.int)
#> array([1, 2, 3])

np.array([1, 2, 3], dtype=np.float)
#> array([1., 2., 3.])

np.array([1, 2, 3], dtype=np.complex)
#> array([1.+0.j, 2.+0.j, 3.+0.j])

np.sqrt(-1, dtype=complex) 
#> 1j

 

*p.s 또한 .astype으로 데이터 변환 가능

data= np.array([1, 2, 3], dtype=np.float)
#> array([1., 2., 3.])

data.astype(np.int)
#> array([1, 2, 3])

 

*p.s 복소수 같은 경우, .real과 imag로 실수/허수 부분 추출 가능

data.real
data.imag

 

 

4. Generating Arrays: Basic Functions

① array: The elements as given in the argument

② zeros: With specific dimensions and data type filled with zeros

③ ones: With specific dimensions and data type flled with ones

④ diag: With diagonal values as specified and zeros elsewhere

⑤ arrange: With evenly spaced values between the specified start, end, and increment values, 지정한 간격의 등차수열을 만듦

⑥  linspace: With evenly spaced values between spacified start and end values, using a specified number of elements, 시작값과 끝값(포함) 사이, 간격이 동일한 n개의 숫자로 이루어진 배열 만듦

⑦ logspace: With values that are logarithmically spaced between the given start and end values,, log 기준

⑧ meshgrid: 1차원 벡터 여러개를 통해 다차원 좌표평면의 좌표를 반환

⑨ random.rand: 0부터 1사이의 값에서 균일 분포를 통해 숫자 랜덤으로 추출하여 배열 생성

⑩ empty: 초기화되지 않은 값으로 배열을 생성 (메모리도 초기화되지 않은 상태에서 생성)

⑪ identity: 대각선 원소는 1, 그 외에는 0인 정방행렬 생성

⑫ eye(n, m, k): nxm의 행렬을 만들되, 대각선으로 1을 생성할 시작 열을 k로 지정

np.zeros((2,3))
#> array([[0., 0., 0.],
#>       [0., 0., 0.]])

np.ones(4)
#> array([1., 1., 1., 1.])

np.full(3,3.2)
#> array([3.2, 3.2, 3.2])

data = np.ones(4)
data.fill(3)
#> array([3., 3., 3., 3.])

np.arange(0,12,4)
#> array([0, 4, 8])

np.linspace(0,12,4)
#> array([ 0., 4., 8., 12.])

np.logspace(0,2,3)
#> array([ 1., 10., 100.])

x = np.array([-1,0,1])
y = np.array([-2,0,2])
X,Y = np.meshgrid(x,y)
print(X)
#> [[-1 0 1]
#>  [-1 0 1]
#>  [-1 0 1]]

print(Y)
#> [[-2 -2 -2]
#>  [ 0 0 0]
#>  [ 2 2 2]]

np.random.rand(2)
#> array([0.78, 0.09])

np.identity(3)
#> array([[1., 0., 0.],
#>        [0., 1., 0.],
#>        [0., 0., 1.]])

np.eye(2, k=1)
#> array([[0., 1.],
#>        [0., 0.]])

np.eye(2, k=-1)
#> array([[0., 0.],
#>        [1., 0.]])

np.diag(np.arange(0, 30, 10))
#> array([[ 0, 0, 0],
#>        [ 0, 10, 0],
#>        [ 0, 0, 20]])

 

 

5. Indexing and Slicing

① A[m]: 0부터 시작해 인덱스 m번째 요소를 추출

② A[-m]: 끝에서부터 m번째 요소 추출

③ A[m:n]: 인덱스 m번째 요소에서 인덱스 (n-1)번째 요소까지 추출

④ A[ : ]: 모든 요소 추출

⑤ A[ :n]: 인덱스 0번째 요소에서 인덱스 (n-1)번째 요소까지 추출

⑥ A[m:n:p': 인덱스 m번째 요소에서부터 (n-1)번째 요소까지, p씩 건너뛰면서 요소 추출

⑦  A[ : :-1]: 모든 요소를 역순으로 추출

a = np.arange(0, 11)
a[0:5:2]
#> array([0, 2, 4])

a[ : :-2]
#> array([10, 8, 6, 4, 2, 0])

#조건을 이용해서 추출 가능
A = np.linspace(0, 1, 11)
A[A > 0.5]
#> array([0.6, 0.7, 0.8, 0.9, 1. ]

 

 

6. Reshaping and Resizing

① reshape: 배열의 모양을 변경. 단 안에 있는 요소 개수가 같을 때만 가능

② vstack: 수직선 방향대로 배열을 쌓음

③ hstack: 수평선 방향대로 배열을 쌓음

④ append: 한 요소를 배열에 추가

⑤ reszie: 배열의 사이즈를 변경. 만약 요소의 개수가 같지 않으면(특히 불충분하다면), 요소를 반복하여 명령한 사이즈대로 배열 생성

⑥ concatenate: 배열끼리 서로 붙여 새 배열 생성

⑦ ndarray.flatten: n차원의 배열을 '복사'하여 1차원의 배열로 만듦 (값 변경시 원본 배열에는 영향을 주지 않음)

data = np.array([[1,2],[3,4]])
np.reshape(data, (1, 4))
#> array([[1, 2, 3, 4]])

data = np.arange(5)
np.vstack((data, data, data))
#> array([[0, 1, 2, 3, 4],
#>        [0, 1, 2, 3, 4],
#>        [0, 1, 2, 3, 4]])
np.hstack((data, data))
#> array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4])

a = np.arange(3)
b = np.arange(4)
np.concatenate((a, b))
#> array([0, 1, 2, 0, 1, 2, 3])

np.append(a, [3,4,5])
array([0, 1, 2, 3, 4, 5])

np.resize(b, (2, 3))
#> array([[0, 1, 2],
#>        [3, 0, 1]])

 

 

7. Elementary Mathematical Functions

① cos, sin, tan: 삼각함수

② arccos, arcsin...: 역삼각함수

③ cosh, sinh...: 쌍곡선함수

④ arccosh, arcsinh...: 역쌍곡선함수

⑤ sqrt: 루트

⑥ exp: 자연지수함수

⑦ log, log2, log10...: 로그함수(log: 자연로그함수)

⑧ pi: 파이

np.cos(np.pi)
#> -1.0
np.sin(np.pi)
#> 0
np.tan(np.pi)
#> 0

np.sqrt(4)
#> 2.0

np.log2(8)
#> 3.0
np.log10(100)
#> 2.0

 

 

8. Elementary Mathematical Operations

① add, subtract, multiply, divide: 두 numpy 배열에 대해 덧셈, 뺄셈, 곱셈, 나눗셈 수행

② power(a, b): a의 b제곱

③ remainder: 나눗셈의 나머지 반환

④ reciprocal: 각 요소에 역수를 취해줌

⑤ real, imag, conj: 배열 각 요소들의 실수, 허수, 복소수 부분 반환

⑥ sign: sign함수 반환값

⑦ abs: 절댓값 반환

⑧ round(a, b): a라는 수를 소수점 아래 b번쨰 자리까지 반올림(b+1번째 자리에서 반올림)

a = [1, 2, 3]
b = [2, 4, 6]
np.add(a, b)
#> array([3, 6, 9])
np.subtract(b, a)
#> array([1, 2, 3])
np.multiply(a, b)
#> array([ 2, 8, 18])
np.divide(b, a)
#> array([2., 2., 2.])

np.power(2, 3)
#> 8
np.remainder(8, 3)
#> 2
np.reciprocal(0.5)
#> 2.0
np.abs(-5.0)
#> 5.0
np.sign(-5.0)
#> -1.0
np.round(3.4124, 2)
#> 3.41

 

 

9. Calculating Aggregates

① mean: 배열의 평균

② std: 배열의 표준편차

③ var: 배열의 분산

④ sum: 배열 내 모든 요소들의 합

⑤ prod: 배열 내 모든 요소들의 곱

⑥ min, max: 배열 내 최소값 / 최대값

⑦ argmin, argmax: 배열 내 최소값의 위치 / 최대값의 위치

⑧ all: 배열 내 모든 원소들이 0이 아니면 TRUE 반환

⑨ any: 배열 내 한 요소라도 0이 아니면 TRUE 반환

a = np.arange(0, 10)

np.mean(a)
#> 4.5
np.std(a)
#> 2.8722813232690143
np.var(a)
#> 8.25
np.sum(a)
#> 45
np.prod(a)
#> 0
print(np.min(a),np.max(a))
#> 0 9
np.argmin(a), np.argmax(a)
#> (0, 9)
np.all(a)
#> False
np.any(a)
#> True

 

 

9. Conditional and Logical Expressions

① where(a, b, c): a라는 조건에 부합하는 요소들은 b의 형태로 반환하고, 그렇지 않으면 c의 형태로 반환

② choose(a, b): b라는 배열에서 인덱스 a번째 요소 반환

③ select([조건1, 조건2...], [값1, 값2...]): 각 조건에 맞는 요소들은 주어진 값의 형태로 반환

④ nonzero: 배열의 요소들 중 0이 아닌 값들의 인덱스 반환

⑤ logical_and: AND 논리연산 수행, True/False로 값들 반환

⑥ logical_or, logical_xor: OR / XOR 논리연산 수행, True/False로 값들 반환

⑦ logical_not: NOT 논리연산 수행

a = np.linspace(0, 16, 5)

np.where(a<5, a, 10*a)
#> array([ 0., 4., 80., 120., 160.])
np.choose(2, a)
#> 8.0
np.nonzero(a)
#> array([1, 2, 3, 4]
np.select([a<2, a>=2], [a-1, a**2])
#> array([ -1., 16., 64., 144., 256.])
np.logical_and(a>1, a<10)
#> array([False, True, True, False, False])
np.logical_or(a<1, a>15)
#> array([True, False, False, False, True])
np.logical_not(a>5)
#> array([True, True, False, False, False])

 

 

10. Array Operations

① transpose, ndarray.transpose, ndarray.T: 배열 transpose

② fliplr, flipud: 각 행들/열들의 요소에 역순을 취함

③ rot90: 첫 두 축을 90도로 회전

④ sort, ndarray.sort: 주어진 축을 기준으로 배열의 요소들을 정렬

mat = np.arange(9).reshape(3, 3)
#> array([[0, 1, 2],
#>        [3, 4, 5],
#>        [6, 7, 8]])

np.transpose(mat)
#> array([[0, 3, 6],
#>        [1, 4, 7],
#>        [2, 5, 8]])

np.fliplr(mat)
#> array([[2, 1, 0],
#>        [5, 4, 3],
#>        [8, 7, 6]])

np.flipud(mat)
#> array([[6, 7, 8],
#>        [3, 4, 5],
#>        [0, 1, 2]])

np.rot90(mat)
#> array([[2, 5, 8],
#>        [1, 4, 7],
#>        [0, 3, 6]])

c = [[2,3,1], [9,8,7]]
np.sort(c)
#> array([[1, 2, 3],
#>        [7, 8, 9]])

 

 

11. Matrix Operations

① dot: 두 배열에 행렬 곱셈을 취함

② inner: 두 배열 사이에 inner product(scalar multiplication)

③ cross: 두 배열 사이에 cross product

④ outer: 두 배열 사이에 outer product(tensor product of vectors)

A = np.arange(1, 7).reshape(2, 3)
#> array([[1, 2, 3],
#>        [4, 5, 6]])
B = np.arange(1, 7).reshape(3, 2)
#> array([[1, 2],
#>        [3, 4],
#>        [5, 6]])

np.dot(A, B)
#> array([[22, 28],
#>        [49, 64]])

np.outer(B, A)
#> array([[1, 2, 3, 4, 5, 6],
#>        [2, 4, 6, 8, 10, 12],
#>        [3, 6, 6, 12, 15, 18],
#>        [4, 8, 12, 16, 20, 24],
#>        [5, 10, 15, 20, 25, 30],
#>        [6, 12, 18, 24, 30, 36]])

c = [2, 3, 4]
d = [4, 5, 6]
np.inner(c, d)
#> 47
np.cross(c, d)
#> array([-2, 4, -2])