데이터분석/Python

NumPy Practice

버섯도리 2022. 5. 9. 11:22

import numpy as np

 

 

def n_size_ndarray_creation(n, dtype=np.int):

    return np.array(range(n**2), dtype=dtype).reshape(n,n)

 

n_size_ndarray_creation(3)

 

 

def zero_or_one_or_empty_ndarray(shape, type=0, dtype=np.int):

    if type == 0:

        X = np.zeros(shape=shape, dtype=dtype)

    elif type == 1:

        X = np.ones(shape=shape, dtype=dtype)

    else:

        X = np.empty(shape=shape, dtype=dtype)

    return X

 

zero_or_one_or_empty_ndarray(shape=(2,2), type=1)

zero_or_one_or_empty_ndarray(shape=(3,3), type=99)

 

 

def change_shape_of_ndarray(X, n_row):

    return X.flatten() if n_row==1 else X.reshape(n_row,-1)

 

X = np.ones((32,32), dtype=np.int)

change_shape_of_ndarray(X, 1)

change_shape_of_ndarray(X, 512)

 

 

def concat_ndarray(X_1, X_2, axis):

    try:

        if axis == 0:

            return np.vstack((X_1, X_2))

        else:

            return np.hstack((X_1, X_2))

        # return np.concatenate( (X_1,X_2), axis=axis)

    except ValueError:

        return False

 

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

b = np.array([[5, 6]])

 

concat_ndarray(a, b, 0)

concat_ndarray(a, b, 1)

 

a = np.array([1, 2])

b = np.array([5, 6, 7])

 

concat_ndarray(a, b, 1)

concat_ndarray(a, b, 0)

 

 

def normalize_ndarray(X, axis=99, dtype=np.float32):

    X = X.astype(dtype)

    n_row, n_column = X.shape

    if axis == 99:

        Z = (X-np.mean(X)) / np.std(X)

    elif axis == 1:

        Z = (X-np.mean(X, axis).reshape(n_row,-1)) / np.std(X, axis).reshape(n_row,-1)

    else:

        Z = (X-np.mean(X, axis)) / np.std(X, axis)

    return Z

 

X = np.arange(12, dtype=np.float32).reshape(6,2)

X

 

normalize_ndarray(X)

normalize_ndarray(X, 1)

normalize_ndarray(X, 0)

 

 

def boolean_index(X, condition):

    return np.where(eval(str("X") + condition))

 

X = np.arange(32, dtype=np.float32).reshape(4, -1)

boolean_index(X, "== 3")

 

X = np.arange(32, dtype=np.float32)

boolean_index(X, "> 6")

 

 

def find_nearest_value(X, target_value):

    return X[np.argmin(np.abs(X - target_value))]

 

X = np.random.uniform(0, 1, 100)

target_value = 0.3

 

find_nearest_value(X, target_value)

 

 

def get_n_largest_values(X, n):

    return X[np.argsort(X)[::-1][:n]]

    # return np.sort(X)[::-1][:n]

 

X = np.random.uniform(0, 1, 100)

 

get_n_largest_values(X, 3)

get_n_largest_values(X, 5)

 

 

 

 

 

 

 

참조 : 부스트코스(http://www.boostcourse.org) -> 머신러닝을 위한 파이썬