# NumPy Cheat Sheet

AIVILLAIN·2023년 3월 6일
0

# Importing NumPy

import numpy as np

# Creating Arrays

# Create a 1-D array
arr = np.array([1, 2, 3])

# Create a 2-D array
arr = np.array([[1, 2, 3], [4, 5, 6]])

# Create an array with zeros
arr = np.zeros((3, 4))

# Create an array with ones
arr = np.ones((2, 3))

# Create an array with random values
arr = np.random.random((2, 3))

# Accessing Array Elements

# Access an element of a 1-D array
arr = np.array([1, 2, 3])
print(arr[0]) # 1

# Access a slice of a 1-D array
arr = np.array([1, 2, 3, 4, 5])
print(arr[1:4]) # [2, 3, 4]

# Access an element of a 2-D array
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr[0, 1]) # 2

# Access a slice of a 2-D array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr[0:2, 1:3]) # [[2, 3], [5, 6]]

# Reshaping Arrays

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

# Flattening Arrays

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

# Transposing Arrays

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

# Basic Array Operations

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
new_arr = arr1 + arr2

# Mathematical Functions

arr = np.array([1, 2, 3])
new_arr = np.sqrt(arr)

# Statistical Functions

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

# Linear Algebra

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

# Saving and Loading Arrays

arr = np.array([1, 2, 3, 4, 5])
np.save('my_array', arr)
arr = np.load('my_array.npy')

# Broadcasting

arr1 = np.array([1, 2, 3])
arr2 = 2
new_arr = arr1 * arr2

# Concatenating Arrays

arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
new_arr = np.concatenate((arr1, arr2))

# Stacking Arrays

arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
new_arr = np.hstack((arr1, arr2))

# Slicing and Masking

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

# Unique Values

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

# Sorting Arrays

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

# File Input and Output

arr = np.array([1, 2, 3, 4, 5])
np.savetxt('my_array.txt', arr)
arr = np.loadtxt('my_array.txt')

# Fourier Transforms

import matplotlib.pyplot as plt

t = np.linspace(0, 1, 100)
y = np.sin(2 * np.pi * 5 * t)
fft_y = np.fft.fft(y)

plt.plot(fft_y)

# Masked Arrays

arr = np.array([1, 2, -999, 4, -999, 6])
mask = arr != -999
new_arr = arr[mask]

# Reference

Numpy Official Documentation

소신있는 오픈마인드