KR_ExternalLibrary - somaz94/python-study GitHub Wiki
ํ์ด์ฌ ์ธ๋ถ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ ํ์ด์ฌ ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ํฌํจ๋์ง ์์ ๋ณ๋์ ํจํค์ง๋ก, ํน์ ๊ธฐ๋ฅ์ ๋ ํจ์จ์ ์ผ๋ก ๊ตฌํํ๊ฑฐ๋ ํน์ํ ๊ธฐ๋ฅ์ ์ ๊ณตํ๋ค. ์ด๋ฌํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ค์ ํจํค์ง ๊ด๋ฆฌ์๋ฅผ ํตํด ์ค์นํ์ฌ ์ฌ์ฉํ ์ ์๋ค.
โ ์ธ๋ถ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ฌ์ฉ ์ด์ :
- ๊ฐ๋ฐ ์๊ฐ ๋จ์ถ ๋ฐ ์ฝ๋ ์ ๊ฐ์
- ์ ๋ฌธ๊ฐ๋ค์ด ์ต์ ํํ ์ฝ๋ ํ์ฉ ๊ฐ๋ฅ
- ํน์ ๋ถ์ผ(๋ฐ์ดํฐ ๊ณผํ, ์น ๊ฐ๋ฐ ๋ฑ)์ ๋ณต์กํ ๊ธฐ๋ฅ ์ฝ๊ฒ ๊ตฌํ
- ์ปค๋ฎค๋ํฐ ์ง์๊ณผ ์ง์์ ์ธ ๊ฐ์
ํ์ด์ฌ์ ๊ธฐ๋ณธ ํจํค์ง ๊ด๋ฆฌ์๋ก, ์ธ๋ถ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ค์นํ๊ณ ๊ด๋ฆฌํ๋ ๋๊ตฌ๋ค.
# ํจํค์ง ์ค์น
pip install package_name
# ํน์ ๋ฒ์ ์ค์น
pip install package_name==1.0.4
# ๋ฒ์ ๋ฒ์ ์ง์
pip install "package_name>=1.0.0,<2.0.0"
# ํจํค์ง ์ ๊ฑฐ
pip uninstall package_name
# ํจํค์ง ์
๊ทธ๋ ์ด๋
pip install --upgrade package_name
# ์ค์น๋ ํจํค์ง ๋ชฉ๋ก
pip list
# ํจํค์ง ์ ๋ณด ํ์ธ
pip show package_name
# requirements.txt์์ ์ผ๊ด ์ค์น
pip install -r requirements.txt
โ pip ๊ณ ๊ธ ํ์ฉ๋ฒ:
- ์บ์ ์ฌ์ฉ:
pip install --cache-dir ./pip-cache package_name
- ํน์ ์ธ๋ฑ์ค ์ฌ์ฉ:
pip install -i https://pypi.org/simple/ package_name
- ์์กด์ฑ ๋ค์ด์ด๊ทธ๋จ:
pip install pipdeptree
ํpipdeptree
์คํ - pip ์์ฒด ์
๊ทธ๋ ์ด๋:
python -m pip install --upgrade pip
- ํ ํจํค์ง ์ค์น ์ฐ์ :
pip install --prefer-binary package_name
ํ๋ก์ ํธ๋ณ ๊ฒฉ๋ฆฌ๋ ํ์ด์ฌ ํ๊ฒฝ์ ๋ง๋ค์ด ์์กด์ฑ ์ถฉ๋์ ๋ฐฉ์งํ๋ค.
# ๊ฐ์ํ๊ฒฝ ์์ฑ (virtualenv ์ฌ์ฉ)
pip install virtualenv # ๋จผ์ virtualenv ์ค์น
virtualenv venv_name # ๊ฐ์ํ๊ฒฝ ์์ฑ
# ๊ฐ์ํ๊ฒฝ ์์ฑ (Python ๋ด์ฅ venv ๋ชจ๋ ์ฌ์ฉ)
python -m venv venv_name
# ๊ฐ์ํ๊ฒฝ ํ์ฑํ (Linux/Mac)
source venv_name/bin/activate
# ๊ฐ์ํ๊ฒฝ ํ์ฑํ (Windows)
venv_name\Scripts\activate
# ๊ฐ์ํ๊ฒฝ ๋นํ์ฑํ
deactivate
# ํ์ฌ ๊ฐ์ํ๊ฒฝ์ ํจํค์ง ๋ชฉ๋ก ์ ์ฅ
pip freeze > requirements.txt
โ ๊ฐ์ํ๊ฒฝ ๋ชจ๋ฒ ์ฌ๋ก:
- ํ๋ก์ ํธ๋ณ๋ก ๋ณ๋์ ๊ฐ์ํ๊ฒฝ ์์ฑ
- ๊ฐ๋ฐ/ํ ์คํธ/๋ฐฐํฌ ํ๊ฒฝ ๋์ผํ๊ฒ ๊ตฌ์ฑ
-
requirements.txt
๋ก ์์กด์ฑ ๋ช ์ - ๊ณต์ ์ ๊ฐ์ํ๊ฒฝ ํด๋(.venv, venv ๋ฑ)๋ gitignore์ ์ถ๊ฐ
- ๊ฐ์ํ๊ฒฝ ๊ฒฝ๋ก์ ๊ณต๋ฐฑ์ด๋ ํน์๋ฌธ์ ํผํ๊ธฐ
๋ฐ์ดํฐ ๊ณผํ ๋ถ์ผ์์ ๋๋ฆฌ ์ฌ์ฉ๋๋ ํจํค์ง ๋ฐ ํ๊ฒฝ ๊ด๋ฆฌ ์์คํ ์ด๋ค.
# ํจํค์ง ์ค์น
conda install package_name
# ํน์ ์ฑ๋์์ ์ค์น
conda install -c conda-forge package_name
# ํ๊ฒฝ ์์ฑ
conda create -n env_name python=3.9
# ํ๊ฒฝ ํ์ฑํ
conda activate env_name
# ํ๊ฒฝ ๋นํ์ฑํ
conda deactivate
# ์ค์น๋ ํจํค์ง ๋ชฉ๋ก
conda list
# ํ๊ฒฝ ๋ด๋ณด๋ด๊ธฐ
conda env export > environment.yml
# ํ๊ฒฝ ๊ฐ์ ธ์ค๊ธฐ
conda env create -f environment.yml
โ conda์ ์ฅ์ :
- ํ์ด์ฌ ํจํค์ง๋ฟ ์๋๋ผ C/C++ ๋ฑ ๋น-ํ์ด์ฌ ์์กด์ฑ๋ ๊ด๋ฆฌ
- ๋ฐ์ด๋๋ฆฌ ํจํค์ง ์ ๊ณต์ผ๋ก ์ปดํ์ผ ๋ฌธ์ ๊ฐ์
- ํ๊ฒฝ ๊ด๋ฆฌ ๊ธฐ๋ฅ์ด ํตํฉ๋์ด ์์
- ๊ณผํ ๊ณ์ฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ์ต์ ํ
ํ๋์ ์ธ Python ํจํค์ง ๋ฐ ์์กด์ฑ ๊ด๋ฆฌ ๋๊ตฌ๋ค.
# Poetry ์ค์น
pip install poetry
# ์ ํ๋ก์ ํธ ์์ฑ
poetry new project-name
# ๊ธฐ์กด ํ๋ก์ ํธ์ Poetry ์ถ๊ฐ
cd project-name
poetry init
# ํจํค์ง ์ถ๊ฐ
poetry add package-name
poetry add package-name==1.0.0
poetry add package-name@^2.0.0
# ๊ฐ๋ฐ ์์กด์ฑ ์ถ๊ฐ
poetry add --dev pytest
# ์์กด์ฑ ์ค์น
poetry install
# ์คํฌ๋ฆฝํธ ์คํ
poetry run python script.py
# ๊ฐ์ํ๊ฒฝ ์ ์ง์
poetry shell
โ Poetry ํน์ง:
- ์์กด์ฑ ํด๊ฒฐ ์๊ณ ๋ฆฌ์ฆ ๊ฐ์
- ๋ฝ ํ์ผ๋ก ์ฌํ ๊ฐ๋ฅํ ํ๊ฒฝ ๋ณด์ฅ
- ํ๋ก์ ํธ ๊ตฌ์ฑ๊ณผ ํจํค์ง ๊ฒ์ ๊ธฐ๋ฅ ํตํฉ
- pyproject.toml์ ์ฌ์ฉํ ํ๋์ ํจํค์ง ๊ตฌ์ฑ
import numpy as np
# ๋ฐฐ์ด ์์ฑ
arr = np.array([1, 2, 3, 4, 5])
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# ํน์ ๋ฐฐ์ด ์์ฑ
zeros = np.zeros((3, 4)) # 0์ผ๋ก ์ฑ์์ง 3x4 ๋ฐฐ์ด
ones = np.ones((2, 3)) # 1๋ก ์ฑ์์ง 2x3 ๋ฐฐ์ด
rng = np.arange(0, 10, 0.5) # 0๋ถํฐ 10๊น์ง 0.5 ๊ฐ๊ฒฉ ๋ฐฐ์ด
linsp = np.linspace(0, 1, 5) # 0๋ถํฐ 1๊น์ง 5๊ฐ ๊ท ๋ฑ ๋ถํ ๋ฐฐ์ด
rand = np.random.random((2, 2)) # 0~1 ์ฌ์ด ๋์ 2x2 ๋ฐฐ์ด
# ๋ฐฐ์ด ์ฐ์ฐ (์์๋ณ)
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(a + b) # [5, 7, 9]
print(a * b) # [4, 10, 18]
print(a ** 2) # [1, 4, 9]
print(np.sin(a)) # ์ฌ์ธ ํจ์ ์ ์ฉ
# ํ๋ ฌ ์ฐ์ฐ
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print(np.dot(a, b)) # ํ๋ ฌ ๊ณฑ
print(a @ b) # ํ๋ ฌ ๊ณฑ (Python 3.5+)
print(np.linalg.inv(a)) # ์ญํ๋ ฌ
print(np.linalg.det(a)) # ํ๋ ฌ์
# ํต๊ณ ํจ์
data = np.array([1, 2, 3, 4, 5])
print(np.mean(data)) # ํ๊ท
print(np.median(data)) # ์ค์๊ฐ
print(np.std(data)) # ํ์คํธ์ฐจ
print(np.var(data)) # ๋ถ์ฐ
print(np.max(data)) # ์ต๋๊ฐ
print(np.min(data)) # ์ต์๊ฐ
print(np.sum(data)) # ํฉ๊ณ
# ์ฐจ์ ์กฐ์
arr = np.array([1, 2, 3, 4, 5, 6])
arr_reshaped = arr.reshape(2, 3) # 2x3 ํ๋ ฌ๋ก ์ฌ๊ตฌ์ฑ
arr_transposed = arr_reshaped.T # ์ ์น
โ NumPy ํน์ง ๋ฐ ์ฅ์ :
- ๋ค์ฐจ์ ๋ฐฐ์ด ๊ฐ์ฒด๋ก ํจ์จ์ ์ธ ๋ฐ์ดํฐ ์ฒ๋ฆฌ
- ๋น ๋ฅธ ๋ฐฐ์ด ์ฐ์ฐ๊ณผ ๋ธ๋ก๋์บ์คํ ๊ธฐ๋ฅ
- ์ ํ๋์, ํธ๋ฆฌ์ ๋ณํ ๋ฑ ์ํ ํจ์ ์ ๊ณต
- C/C++๋ก ๊ตฌํ๋์ด ํ์ด์ฌ๋ณด๋ค ๋น ๋ฅธ ์ฑ๋ฅ
- ๋ง์ ๊ณผํ ๊ณ์ฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ๊ธฐ๋ฐ
import pandas as pd
import numpy as np
# Series ์์ฑ (1์ฐจ์ ๋ฐ์ดํฐ)
s = pd.Series([1, 3, 5, np.nan, 6, 8])
print(s)
# DataFrame ์์ฑ (2์ฐจ์ ๋ฐ์ดํฐ)
dates = pd.date_range('20230101', periods=6)
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))
print(df)
# ๋์
๋๋ฆฌ๋ก๋ถํฐ DataFrame ์์ฑ
data = {
'์ด๋ฆ': ['๊น์ฒ ์', '์ด์ํฌ', '๋ฐ์ง๋ฏผ'],
'๋์ด': [25, 28, 22],
'์ฑ๋ณ': ['๋จ', '์ฌ', '๋จ']
}
df = pd.DataFrame(data)
print(df)
# ํ์ผ ์ฝ๊ณ ์ฐ๊ธฐ
# df.to_csv('data.csv') # CSV ํ์ผ๋ก ์ ์ฅ
# df.to_excel('data.xlsx', sheet_name='Sheet1') # Excel ํ์ผ๋ก ์ ์ฅ
# csv_df = pd.read_csv('data.csv') # CSV ํ์ผ ์ฝ๊ธฐ
# excel_df = pd.read_excel('data.xlsx') # Excel ํ์ผ ์ฝ๊ธฐ
# ๋ฐ์ดํฐ ์กฐํ
print(df.head(2)) # ์ฒ์ 2ํ
print(df.tail(2)) # ๋ง์ง๋ง 2ํ
print(df['์ด๋ฆ']) # ํน์ ์ด ์ ํ
print(df[0:2]) # ํ ์ฌ๋ผ์ด์ฑ
print(df.loc[0]) # ํน์ ํ ์ ํ (๋ ์ด๋ธ ๊ธฐ์ค)
print(df.iloc[1:3, 0:2]) # ํ/์ด ์ฌ๋ผ์ด์ฑ (์์น ๊ธฐ์ค)
# ๋ฐ์ดํฐ ํํฐ๋ง
print(df[df['๋์ด'] > 25]) # ์กฐ๊ฑด์ ๋ง๋ ํ ์ ํ
print(df[(df['๋์ด'] > 22) & (df['์ฑ๋ณ'] == '๋จ')]) # ๋ณตํฉ ์กฐ๊ฑด
# ๋ฐ์ดํฐ ์ฒ๋ฆฌ
df['์ถ์๋
๋'] = 2023 - df['๋์ด'] # ์ ์ด ์ถ๊ฐ
df = df.drop(columns=['์ถ์๋
๋']) # ์ด ์ญ์
df = df.rename(columns={'๋์ด': '์ฐ๋ น'}) # ์ด ์ด๋ฆ ๋ณ๊ฒฝ
df['์ฐ๋ น'] = df['์ฐ๋ น'] + 1 # ๊ฐ ์์
# ๊ทธ๋ฃนํ ๋ฐ ์ง๊ณ
grouped = df.groupby('์ฑ๋ณ')
print(grouped['์ฐ๋ น'].mean()) # ์ฑ๋ณ ๊ธฐ์ค ํ๊ท ์ฐ๋ น
print(grouped.size()) # ์ฑ๋ณ ๊ธฐ์ค ๊ฐ์
# ๊ฒฐ์ธก์น ์ฒ๋ฆฌ
df_with_na = df.copy()
df_with_na.loc[1, '์ฐ๋ น'] = None
print(df_with_na.isna().sum()) # ์ด๋ณ ๊ฒฐ์ธก์น ๊ฐ์
df_filled = df_with_na.fillna(0) # ๊ฒฐ์ธก์น 0์ผ๋ก ์ฑ์ฐ๊ธฐ
df_dropped = df_with_na.dropna() # ๊ฒฐ์ธก์น ์๋ ํ ์ญ์
โ pandas ํต์ฌ ๊ธฐ๋ฅ:
- ๋ฐ์ดํฐ ์ ์ ๋ฐ ์ ์ฒ๋ฆฌ ๊ธฐ๋ฅ ์ ๊ณต
- SQL๊ณผ ์ ์ฌํ ๋ฐ์ดํฐ ์กฐ์ ๊ธฐ๋ฅ
- ๋ค์ํ ํ์ผ ํ์ ์ ์ถ๋ ฅ ์ง์
- ์๊ณ์ด ๋ฐ์ดํฐ ์ฒ๋ฆฌ๋ฅผ ์ํ ํนํ ๊ธฐ๋ฅ
- ๊ฒฐ์ธก์น, ์ด์์น ์ฒ๋ฆฌ ๋ฐ ๋ฐ์ดํฐ ๋ณํ ๋๊ตฌ
import matplotlib.pyplot as plt
import numpy as np
# ๊ธฐ๋ณธ ์ ๊ทธ๋ํ
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure(figsize=(10, 6))
plt.plot(x, y, label='sin(x)')
plt.title('์ฌ์ธ ํจ์ ๊ทธ๋ํ')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.grid(True)
plt.legend()
# plt.savefig('sin_graph.png') # ์ด๋ฏธ์ง๋ก ์ ์ฅ
# plt.show()
# ์ฌ๋ฌ ๊ทธ๋ํ ๊ทธ๋ฆฌ๊ธฐ
plt.figure(figsize=(10, 6))
plt.plot(x, np.sin(x), 'b-', label='sin(x)') # ํ๋์ ์ค์
plt.plot(x, np.cos(x), 'r--', label='cos(x)') # ๋นจ๊ฐ์ ์ ์
plt.title('์ผ๊ฐํจ์ ๊ทธ๋ํ')
plt.legend()
# plt.show()
# ์๋ธํ๋กฏ (์ฌ๋ฌ ๊ทธ๋ํ ๋ฐฐ์น)
plt.figure(figsize=(12, 8))
plt.subplot(2, 2, 1) # 2x2 ๊ทธ๋ฆฌ๋์ ์ฒซ ๋ฒ์งธ
plt.plot(x, np.sin(x))
plt.title('sin(x)')
plt.subplot(2, 2, 2) # 2x2 ๊ทธ๋ฆฌ๋์ ๋ ๋ฒ์งธ
plt.plot(x, np.cos(x))
plt.title('cos(x)')
plt.subplot(2, 2, 3) # 2x2 ๊ทธ๋ฆฌ๋์ ์ธ ๋ฒ์งธ
plt.plot(x, np.sin(2*x))
plt.title('sin(2x)')
plt.subplot(2, 2, 4) # 2x2 ๊ทธ๋ฆฌ๋์ ๋ค ๋ฒ์งธ
plt.plot(x, np.cos(2*x))
plt.title('cos(2x)')
plt.tight_layout() # ๋ ์ด์์ ์๋ ์กฐ์
# plt.show()
# ๋ค์ํ ์ฐจํธ ์ ํ
plt.figure(figsize=(15, 10))
# ๋ง๋ ๊ทธ๋ํ
plt.subplot(2, 3, 1)
categories = ['A', 'B', 'C', 'D']
values = [3, 7, 2, 5]
plt.bar(categories, values)
plt.title('๋ง๋ ๊ทธ๋ํ')
# ์ํ ๋ง๋ ๊ทธ๋ํ
plt.subplot(2, 3, 2)
plt.barh(categories, values)
plt.title('์ํ ๋ง๋ ๊ทธ๋ํ')
# ์ฐ์ ๋
plt.subplot(2, 3, 3)
x = np.random.rand(50)
y = np.random.rand(50)
colors = np.random.rand(50)
sizes = 1000 * np.random.rand(50)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5)
plt.title('์ฐ์ ๋')
# ํ์คํ ๊ทธ๋จ
plt.subplot(2, 3, 4)
data = np.random.randn(1000)
plt.hist(data, bins=30)
plt.title('ํ์คํ ๊ทธ๋จ')
# ํ์ด ์ฐจํธ
plt.subplot(2, 3, 5)
plt.pie(values, labels=categories, autopct='%1.1f%%')
plt.title('ํ์ด ์ฐจํธ')
# ๋ฐ์ค ํ๋กฏ
plt.subplot(2, 3, 6)
data = [np.random.normal(0, std, 100) for std in range(1, 5)]
plt.boxplot(data)
plt.title('๋ฐ์ค ํ๋กฏ')
plt.tight_layout()
# plt.show()
โ matplotlib ๊ธฐ๋ฅ:
- ๋ค์ํ ์ฐจํธ ๋ฐ ์๊ฐํ ์์ฑ
- ์ธ๋ถ์ ์ธ ์คํ์ผ ๋ฐ ๋ ์ด์์ ์ ์ด
- ๊ณ ํ์ง ์ถํ๋ฌผ ์์ค์ ๊ทธ๋ํฝ ์ ์
- ๋ค์ํ ์ถ๋ ฅ ํ์(PNG, PDF, SVG ๋ฑ) ์ง์
- Pandas, NumPy์ ์ ํตํฉ๋จ
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# ํ
๋ง ์ค์
sns.set_theme(style="whitegrid") # ์คํ์ผ ์ค์
# ์ํ ๋ฐ์ดํฐ ์์ฑ
tips = sns.load_dataset('tips') # seaborn ๋ด์ฅ ๋ฐ์ดํฐ
iris = sns.load_dataset('iris') # ๋ค๋ฅธ ๋ด์ฅ ๋ฐ์ดํฐ
# ๊ธฐ๋ณธ ๊ทธ๋ํ
plt.figure(figsize=(15, 10))
# ๋ง๋ ๊ทธ๋ํ (์นด์ดํธํ๋กฏ)
plt.subplot(2, 3, 1)
sns.countplot(x='day', data=tips)
plt.title('์์ผ๋ณ ์๋ ์')
# ์ฐ์ ๋ (์ค์บํฐํ๋กฏ)
plt.subplot(2, 3, 2)
sns.scatterplot(x='total_bill', y='tip', hue='time', data=tips)
plt.title('๊ณ์ฐ์์ ํ์ ๊ด๊ณ')
# ํ๊ท์ ํฌํจ ์ฐ์ ๋
plt.subplot(2, 3, 3)
sns.regplot(x='total_bill', y='tip', data=tips)
plt.title('ํ๊ท์ ํฌํจ ์ฐ์ ๋')
# ๋ค๋ณ๋ ์ฐ์ ๋ ๋งคํธ๋ฆญ์ค
plt.figure(figsize=(10, 8))
sns.pairplot(iris, hue='species')
plt.suptitle('๋ถ๊ฝ ๋ฐ์ดํฐ ๋ค๋ณ๋ ๋ถ์', y=1.02)
# plt.show()
# ํํธ๋งต
plt.figure(figsize=(10, 8))
corr = iris.drop('species', axis=1).corr()
sns.heatmap(corr, annot=True, cmap='coolwarm')
plt.title('์๊ด๊ด๊ณ ํํธ๋งต')
# plt.show()
# ๋ฐ์ด์ฌ๋ฆฐ ํ๋กฏ
plt.figure(figsize=(12, 6))
sns.violinplot(x='day', y='total_bill', hue='sex', data=tips, split=True)
plt.title('์์ผ๋ณ ๊ณ์ฐ์ ๊ธ์ก ๋ถํฌ (์ฑ๋ณ ๊ตฌ๋ถ)')
# plt.show()
# ๋ถํฌ๋ ํ๋กฏ
plt.figure(figsize=(12, 6))
sns.kdeplot(data=tips, x='total_bill', hue='time', fill=True, common_norm=False)
plt.title('์๊ฐ๋๋ณ ๊ณ์ฐ์ ๊ธ์ก ๋ถํฌ')
# plt.show()
โ seaborn ์ฅ์ :
- matplotlib๋ณด๋ค ๋ ๋ฏธํ์ ์ด๊ณ ํต๊ณ์ ์ธ ์๊ฐํ
- ๋ฐ์ดํฐํ๋ ์ ๊ธฐ๋ฐ ์ง๊ด์ ์ธ API
- ๋ณต์กํ ์๊ฐํ๋ฅผ ๊ฐ๋จํ ์์ฑ
- ๋ค๋ณ๋ ๋ฐ์ดํฐ ํ์์ ์ต์ ํ
- ํต๊ณ์ ๊ด๊ณ ํ์์ ์ํ ํนํ ๊ธฐ๋ฅ
from faker import Faker
# ๋ค์ํ ์ธ์ด ์ง์
fake_ko = Faker('ko_KR') # ํ๊ตญ์ด
fake_en = Faker('en_US') # ์์ด(๋ฏธ๊ตญ)
fake_jp = Faker('ja_JP') # ์ผ๋ณธ์ด
# ์๋ ์ค์ (์ฌํ ๊ฐ๋ฅํ ๋ฐ์ดํฐ)
Faker.seed(1234)
fake = Faker('ko_KR')
# ๊ฐ์ธ ์ ๋ณด ์์ฑ
print(fake.name()) # ์ด๋ฆ
print(fake.address()) # ์ฃผ์
print(fake.postcode()) # ์ฐํธ๋ฒํธ
print(fake.phone_number()) # ์ ํ๋ฒํธ
print(fake.email()) # ์ด๋ฉ์ผ
print(fake.company()) # ํ์ฌ๋ช
print(fake.job()) # ์ง์
# ์ธํฐ๋ท ๊ด๋ จ ๋ฐ์ดํฐ
print(fake.user_name()) # ์ฌ์ฉ์ ์ด๋ฆ
print(fake.password()) # ๋น๋ฐ๋ฒํธ
print(fake.ipv4()) # IPv4 ์ฃผ์
print(fake.url()) # URL
print(fake.user_agent()) # ์ฌ์ฉ์ ์์ด์ ํธ
# ๋ ์ง/์๊ฐ ๋ฐ์ดํฐ
print(fake.date_of_birth(minimum_age=20, maximum_age=80)) # ์๋
์์ผ
print(fake.date_this_decade()) # ์ด๋ฒ 10๋
๋ด ๋ ์ง
print(fake.future_date()) # ๋ฏธ๋ ๋ ์ง
print(fake.time()) # ์๊ฐ
# ํ
์คํธ ๋ฐ์ดํฐ
print(fake.text(max_nb_chars=200)) # ํ
์คํธ ์์ฑ
print(fake.paragraph()) # ๋ฌธ๋จ ์์ฑ
print(fake.sentence()) # ๋ฌธ์ฅ ์์ฑ
# ์ปค์คํ
๋ฐ์ดํฐ ์์ฑ๊ธฐ
from faker.providers import BaseProvider
class MyProvider(BaseProvider):
def korean_food(self):
foods = ['๊น์น์ฐ๊ฐ', '๋์ฅ์ฐ๊ฐ', '๋น๋น๋ฐฅ', '๋ถ๊ณ ๊ธฐ', '๊น๋ฐฅ', '๋ก๋ณถ์ด', '์ผ๊ฒน์ด']
return self.random_element(foods)
# ํ๋ก๋ฐ์ด๋ ์ถ๊ฐ
fake.add_provider(MyProvider)
print(fake.korean_food())
# ๋๋ ๋ฐ์ดํฐ ์์ฑ ์์
users = [
{
'id': i,
'name': fake.name(),
'email': fake.email(),
'address': fake.address(),
'phone': fake.phone_number(),
'join_date': fake.date_this_year()
}
for i in range(1, 51) # 50๋ช
๋ฐ์ดํฐ ์์ฑ
]
โ Faker ํ์ฉ ๋ถ์ผ:
- ํ ์คํธ ๋ฐ์ดํฐ ์์ฑ
- ๊ฐ๋ฐ ๋จ๊ณ์์ ์ค์ ๊ฐ์ ๋ฐ์ดํฐ ์ฌ์ฉ
- ๋ฐ์ดํฐ๋ฒ ์ด์ค ์๋ ๋ฐ์ดํฐ ์ค๋น
- ๋ฐ์ดํฐ ์ต๋ช ํ
- ๋ค๊ตญ์ด ์ง์์ผ๋ก ๋ค์ํ ์ง์ญ์ ๋ฐ์ดํฐ ํ์ ์ ๊ณต
import sympy as sp
# ๊ธฐ๋ณธ ๋์ ์ฐ์ฐ
x, y, z = sp.symbols('x y z') # ๊ธฐํธ ๋ณ์ ์ ์
expr = x**2 + 2*x*y + y**2
print(expr)
# ์ ์ ๊ฐ ๋ฐ ์ธ์๋ถํด
expanded = sp.expand((x + y)**3)
print(expanded)
factored = sp.factor(x**3 - y**3)
print(factored)
# ๋ฐฉ์ ์ ํ๊ธฐ
eq1 = sp.Eq(x**2, 4) # x^2 = 4
solution = sp.solve(eq1, x)
print(solution) # [-2, 2]
# ์ฐ๋ฆฝ๋ฐฉ์ ์
eq1 = sp.Eq(x + y, 6)
eq2 = sp.Eq(x - y, 4)
solution = sp.solve((eq1, eq2), (x, y))
print(solution) # {x: 5, y: 1}
# ํ๋ ฌ ์ฐ์ฐ
A = sp.Matrix([[1, 2], [3, 4]])
B = sp.Matrix([[5, 6], [7, 8]])
print(A + B) # ํ๋ ฌ ๋ง์
print(A * B) # ํ๋ ฌ ๊ณฑ์
print(A.det()) # ํ๋ ฌ์
print(A.inv()) # ์ญํ๋ ฌ
print(A.eigenvals()) # ๊ณ ์ ๊ฐ
# ๋ฏธ๋ถ
f = x**3 + 2*x**2 - 5*x + 3
derivative = sp.diff(f, x)
print(derivative) # 3*x^2 + 4*x - 5
# ๋ถ๋ถ ๋ฏธ๋ถ
f_multi = x**2 * y + y**2 * z
df_dx = sp.diff(f_multi, x)
df_dy = sp.diff(f_multi, y)
print(df_dx) # 2*x*y
print(df_dy) # x^2 + 2*y*z
# ์ ๋ถ
integral = sp.integrate(x**2, x)
print(integral) # x^3/3
# ์ ์ ๋ถ
def_integral = sp.integrate(x**2, (x, 0, 1))
print(def_integral) # 1/3
# ๊ทนํ
limit_expr = sp.limit((sp.sin(x))/x, x, 0)
print(limit_expr) # 1
# ๊ธ์ ์ ๊ฐ
series = sp.series(sp.exp(x), x, 0, 5)
print(series) # ํ
์ผ๋ฌ ๊ธ์ ์ ๊ฐ
# ๋ผํ๋ผ์ค ๋ณํ
t = sp.symbols('t', positive=True)
s = sp.symbols('s')
f_t = t**2
F_s = sp.laplace_transform(f_t, t, s)
print(F_s) # (2/s^3, s, True)
# ๋ฏธ๋ถ๋ฐฉ์ ์ ํ๊ธฐ
f = sp.Function('f')
diffeq = sp.Eq(f(x).diff(x, 2) + f(x), 0)
solution = sp.dsolve(diffeq, f(x))
print(solution)
โ SymPy ํต์ฌ ํน์ง:
- ๊ธฐํธ ์ํ ์ฐ์ฐ์ ์ํ ํฌ๊ด์ ์ธ ๋ผ์ด๋ธ๋ฌ๋ฆฌ
- ๋ฐฉ์ ์, ๋ฏธ๋ถ, ์ ๋ถ, ํ๋ ฌ ๋ฑ ๋ค์ํ ์ํ ๊ธฐ๋ฅ
- ์์์ ์ ํํ ํด ๊ณ์ฐ (๊ทผ์ฌ์น๊ฐ ์๋)
- LaTeX ์ถ๋ ฅ ์ง์์ผ๋ก ์ํ ๋ฌธ์ ์์ฑ์ ์ ์ฉ
- ์ ์ฉํ ๊ฒฐ๊ณผ ๋จ์ํ ๋ฐ ๋ณํ ๊ธฐ๋ฅ
import requests
# ๊ธฐ๋ณธ GET ์์ฒญ
response = requests.get('https://api.github.com/events')
print(response.status_code) # ์ํ ์ฝ๋ (200, 404 ๋ฑ)
print(response.headers) # ์๋ต ํค๋
print(response.encoding) # ์ธ์ฝ๋ฉ
print(response.text[:100]) # ์๋ต ๋ด์ฉ (์ฒ์ 100์)
print(response.json()) # JSON ์๋ต ํ์ฑ
# URL ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ
params = {'q': 'python', 'sort': 'stars'}
response = requests.get('https://api.github.com/search/repositories', params=params)
print(response.url) # ์ต์ข
URL ์ถ๋ ฅ
# ์ปค์คํ
ํค๋
headers = {'User-Agent': 'my-app/0.0.1'}
response = requests.get('https://api.github.com/user', headers=headers)
# POST ์์ฒญ
data = {'username': 'user', 'password': 'pass'}
response = requests.post('https://httpbin.org/post', data=data)
# JSON POST ์์ฒญ
json_data = {'name': 'user', 'repos': ['repo1', 'repo2']}
response = requests.post('https://httpbin.org/post', json=json_data)
# ํ์ผ ์
๋ก๋
# files = {'file': open('report.pdf', 'rb')}
# response = requests.post('https://httpbin.org/post', files=files)
# ์ธ์
์ฌ์ฉ (์ฟ ํค ์ ์ง)
session = requests.Session()
session.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
response = session.get('https://httpbin.org/cookies')
print(response.json())
# ํ์์์ ์ค์
try:
response = requests.get('https://httpbin.org/delay/5', timeout=3)
except requests.exceptions.Timeout:
print("์์ฒญ์ด ํ์์์๋์์ต๋๋ค.")
# ์๋ฌ ์ฒ๋ฆฌ
try:
response = requests.get('https://httpbin.org/status/500')
response.raise_for_status() # 4XX, 5XX ์๋ฌ ์ ์์ธ ๋ฐ์
except requests.exceptions.HTTPError as err:
print(f"HTTP ์๋ฌ ๋ฐ์: {err}")
โ requests ์ฃผ์ ๊ธฐ๋ฅ:
- ๊ฐ๊ฒฐํ๊ณ ์ง๊ด์ ์ธ HTTP ์์ฒญ API
- ์๋ JSON ํ์ฑ ๋ฐ ์ธ์ฝ๋ฉ ์ฒ๋ฆฌ
- ์ธ์ ๋ฐ ์ฟ ํค ์ง์
- ํ์ผ ์ ๋ก๋ ๋ฐ ๋ค์ด๋ก๋ ๊ธฐ๋ฅ
- ์ธ์ฆ, ํ๋ก์, ํ์์์ ๋ฑ ๊ณ ๊ธ ๊ธฐ๋ฅ ์ ๊ณต
from flask import Flask, request, jsonify, render_template, redirect, url_for
# ์ ํ๋ฆฌ์ผ์ด์
์์ฑ
app = Flask(__name__)
# ๊ธฐ๋ณธ ๋ผ์ฐํธ
@app.route('/')
def home():
return 'Hello, Flask!'
# ๋ณ์๊ฐ ์๋ ๋ผ์ฐํธ
@app.route('/user/<username>')
def show_user(username):
return f'User: {username}'
# ํ์
๋ณํ (์ ์)
@app.route('/post/<int:post_id>')
def show_post(post_id):
return f'Post ID: {post_id}'
# ์ฌ๋ฌ HTTP ๋ฉ์๋ ์ฒ๋ฆฌ
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
# ๋ก๊ทธ์ธ ๋ก์ง ์ฒ๋ฆฌ
return f'๋ก๊ทธ์ธ ์๋: {username}'
else:
return '''
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
'''
# JSON ์๋ต
@app.route('/api/data')
def get_data():
data = {
'name': 'John',
'age': 30,
'items': ['item1', 'item2']
}
return jsonify(data)
# ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ
@app.route('/search')
def search():
query = request.args.get('q', '')
return f'๊ฒ์์ด: {query}'
# ํ
ํ๋ฆฟ ๋ ๋๋ง
@app.route('/hello/<name>')
def hello(name):
# ์ค์ ๋ก๋ templates/hello.html ํ์ผ ํ์
# return render_template('hello.html', name=name)
return f'<h1>Hello, {name}!</h1>'
# ๋ฆฌ๋ค์ด๋ ์
@app.route('/redirect')
def redirect_example():
return redirect(url_for('home'))
# ์๋ฌ ํธ๋ค๋ฌ
@app.errorhandler(404)
def page_not_found(e):
return '404 - ํ์ด์ง๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค', 404
# ์ ํ๋ฆฌ์ผ์ด์
์คํ
if __name__ == '__main__':
# app.run(debug=True)
pass # ์ค์ ์คํ์ ๋ง๊ธฐ ์ํด pass ์ฌ์ฉ
โ Flask ํน์ง:
- ๋ง์ดํฌ๋ก ์น ํ๋ ์์ํฌ๋ก ํ์ํ ๊ธฐ๋ฅ๋ง ๊ฐ๊ฒฐํ๊ฒ ์ ๊ณต
- ์ฌ์ด ํ์ต ๊ณก์ ๊ณผ ์ง๊ด์ ์ธ ๊ตฌ์กฐ
- ํ์ฅ์ฑ์ด ๋ฐ์ด๋ ํ์์ ๋ฐ๋ผ ๊ธฐ๋ฅ ์ถ๊ฐ ๊ฐ๋ฅ
- ๊ฐ๋ฐ ์๋ฒ ๋ฐ ๋๋ฒ๊ฑฐ ๋ด์ฅ
- RESTful API ๊ฐ๋ฐ์ ์ ํฉ
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
# ๋ฐ์ดํฐ์
๋ก๋
iris = datasets.load_iris()
X = iris.data
y = iris.target
# ๋ฐ์ดํฐ ๋ถํ
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42)
# ๋ฐ์ดํฐ ์ ์ฒ๋ฆฌ (์ค์ผ์ผ๋ง)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# ๋ชจ๋ธ ์ด๊ธฐํ
models = {
'Logistic Regression': LogisticRegression(max_iter=1000),
'Decision Tree': DecisionTreeClassifier(),
'Random Forest': RandomForestClassifier(),
'SVM': SVC()
}
# ๋ชจ๋ธ ํ์ต ๋ฐ ํ๊ฐ
results = {}
for name, model in models.items():
# ๋ชจ๋ธ ํ์ต
model.fit(X_train_scaled, y_train)
# ์์ธก
y_pred = model.predict(X_test_scaled)
# ํ๊ฐ
accuracy = accuracy_score(y_test, y_pred)
report = classification_report(y_test, y_pred)
results[name] = {
'accuracy': accuracy,
'report': report
}
print(f"๋ชจ๋ธ: {name}")
print(f"์ ํ๋: {accuracy:.4f}")
print(f"๋ถ๋ฅ ๋ณด๊ณ ์:\n{report}\n")
# ๋น์ง๋ ํ์ต ์์ - K-means ํด๋ฌ์คํฐ๋ง
kmeans = KMeans(n_clusters=3, random_state=42)
clusters = kmeans.fit_predict(X)
# ์ฐจ์ ์ถ์ - PCA
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)
# ์๊ฐํ (ํด๋ฌ์คํฐ๋ง ๊ฒฐ๊ณผ)
plt.figure(figsize=(12, 5))
# ์ค์ ํด๋์ค
plt.subplot(1, 2, 1)
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y, cmap='viridis')
plt.title('์ค์ ํด๋์ค')
# K-means ํด๋ฌ์คํฐ
plt.subplot(1, 2, 2)
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=clusters, cmap='viridis')
plt.title('K-means ํด๋ฌ์คํฐ๋ง')
# plt.savefig('clustering.png')
# plt.show()
โ scikit-learn ์ฅ์ :
- ํฌ๊ด์ ์ธ ๋จธ์ ๋ฌ๋ ์๊ณ ๋ฆฌ์ฆ ์ ๊ณต
- ์ผ๊ด๋ API๋ก ์ฌ์ด ๋ชจ๋ธ ๊ต์ฒด ๋ฐ ๋น๊ต
- ๋ฐ์ดํฐ ์ ์ฒ๋ฆฌ, ๋ชจ๋ธ ์ ํ, ํ๊ฐ ๋๊ตฌ ํตํฉ
- ์ ๋ฌธ์ํ๋ API์ ํ๋ฐํ ์ปค๋ฎค๋ํฐ
- NumPy, SciPy, pandas์ ํตํฉ
โ ๋ชจ๋ฒ ์ฌ๋ก:
- pip ์ค์น ์ ๊ฐ์ํ๊ฒฝ ์ฌ์ฉ ๊ถ์ฅ
- requirements.txt๋ก ์์กด์ฑ ๊ด๋ฆฌ
- Faker ์ฌ์ฉ ์ seed ์ค์ ์ผ๋ก ์ฌํ ๊ฐ๋ฅํ ๋ฐ์ดํฐ ์์ฑ
- SymPy ์ฌ์ฉ ์ Fraction์ผ๋ก ์ ํํ ๋ถ์ ๊ณ์ฐ
- NumPy, pandas ๋ฑ ๊ณ์ฐ ์ง์ฝ์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ ์ต์ ๋ฒ์ ์ฌ์ฉ
- ์น ๊ฐ๋ฐ ์ Flask ๋๋ฒ๊ทธ ๋ชจ๋๋ ๊ฐ๋ฐ ํ๊ฒฝ์์๋ง ํ์ฑํ
- scikit-learn ๋ชจ๋ธ ์ ์ฅ ์ joblib ์ฌ์ฉ ๊ถ์ฅ
- matplotlib ์๊ฐํ ์ plt.figure()๋ก ํฌ๊ธฐ ๋ช ์์ ์ค์
- ์ธ๋ถ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ฌ์ฉ ์ ๋ฒ์ ํธํ์ฑ ํ์ธ
- ๋์ฉ๋ ๋ฐ์ดํฐ ์ฒ๋ฆฌ ์ ๋ฉ๋ชจ๋ฆฌ ์ฌ์ฉ๋ ๋ชจ๋ํฐ๋ง