Coding/Python

Numpy 라이브러리 모음

폴밴 2022. 2. 21. 10:21

Array

import numpy as np
my_list = [1,2,3]
np.array(my_list)

my_matrix = [[1,2,3],[4,5,6,],[7,8,9,]]
np.array(my_matrix)

Arange

np.arange(11)
np.arange(1,11)
np.arange(1,11,2)  # interval

Zeros, Linspace

np.zeros(3)
np.zeros((5,5))  # matrix = tuple
np.linspace(0,10,3) # linearly spaced in area
np.linspace(0,10,50)

Random

np.random.rand(3) # [0,1)
np.random.randn(2,5) # standard normal
np.random.randint(1,10) # set area of random numbers
np.random.randint(1,10,5)

Reshape

arr = np.arange(25)
arr
arr.reshape(5,5)  # reshape to matrix

Max, Min

ranarr = np.random.randint(0,50,10)
ranarr
ranarr.max()
ranarr.argmax()  # index of maximum value
ranarr.min()
ranarr.argmin()  # index of minimum value

Shape

arr.shape  # Vector (25,)
arr.reshape(1,25)  # 1 x 25 matrix
arr.reshape(1,25).shape

Sum

mat = np.arange(25).reshape(5,5)
mat
np.sum(mat)
np.sum(mat, axis = 0) # sum of rows
np.sum(mat, axis = 1) # sum of columns
mat.dtype # data type

Selection

arr = np.arange(11)
arr
arr[8]
arr[1:5]
arr[0:3]

Broadcasting

arr = np.arange(11)
arr
slice_of_arr = arr[0:5]
slice_of_arr
slice_of_arr[:] = 99
slice_of_arr
arr  # Data is not copied, it's a view of the original way
#Need to be explicit to get copied
arr_copy = arr.copy()
arr_copy
arr_copy[:5] = np.arange(5)
arr_copy
arr

Array Selection

arr_2d = np.arange(25).reshape(5,5)
arr_2d
arr_2d[3]
arr_2d[3][1]
arr_2d[3,1]
arr_2d[:2]
arr_2d[:2,3:]
arr2d = np.zeros((5,5))
arr2d
arr_length = arr2d.shape[0]
for i in range(arr_length):
    arr2d[i] = i
arr2d
arr2d[[2,4]]
arr2d[[3,1]]

Selecting one column

mat = np.arange(25).reshape(5,5)
mat
mat[:3,2]  # selected one column, but output is vector
mat[:3,2:3] # selected one column, but output is column

Conditional Selection

arr = np.arange(11)
arr
arr > 4  # output is binary
arr[arr > 4] # output with only true values

Operations

arr + arr
arr - arr
arr * arr
arr / arr # divided by zero comes with warning -> nan
arr ** 3

Math Functions

np.sqrt(arr)
np.exp(arr)
np.max(arr)
np.sin(arr)
np.log(arr)