똑같은 무언가(객체)를 만들어 낼 수 있는 설계 도면
class Cookie: # 클래스 정의
pass
a = Cookie() # 객체 생성
def 함수명(매개변수):
수행할 문장
class FourCal:
def setdata(self, first, second): # self는 자신의 객체 주소를 참조
self.first = first # setdata 호출 이전에는 존재 X
self.second = second # 호출 이전에 메서드 수행 시 'AttributeError' 오류 발생
def add(self):
result = self.first + self.second
return result
def mul(self):
result = self.first * self.second
return result
def sub(self):
result = self.first - self.second
return result
def div(self):
result = self.first / self.second
return result
>>> a = FourCal()
>>> a.setdata(4, 2)
>>> a.add()
6
>>> a.mul()
8
>>> a.sub()
2
>>> a.div()
2.0
객체 생성 시 자동으로 호출되는 메서드
class FourCal:
def __init__(self, first, second):
self.first = first
self.second = second
__init__로 초기 값 설정class 클래스명(상속할 클래스명)
class MoreFourCal(FourCal):
def pew(self):
result = self.first ** self.second
return result
>>> a = MoreFourCal(4, 2)
>>> a.pow()
16
>>> a.add()
6
부모 클래스(상속한 클래스)의 메서드를 동일한 이름으로 다시 만드는 것
class SafeFourCal(FourCal):
def div(self):
if self.second == 0
return 0
else:
return self.first / self.second
>>> a = SafeFourCal(4, 0)
>>> a.div()
0
연괸된 기능이나 공통 목적을 가진 함수, 변수, 클래스를 모아둔 파일
1_모듈 전체를 불러올 때
import 모듈명
모듈명.변수명()
2) 모듈명 없이 함수명만 쓰고 싶은 경우
from 모듈명 import 모듈함수
모듈함수명()
3) 함수를 여러 개 불러오고 싶은 경우: 쉼표(,)로 구분
from 모듈명 import 모듈함수1, 모듈함수2
4) 모듈의 모든 함수를 불러오는 경우
from 모듈명 import *
전셰계 개발자들이 만든 유용한 프로그램을 모아둔 것으로, 파이썬 설치 시 지동으로 설치됨
| 이름 | 설명 |
|---|---|
| datetime.data() | 연, 월, 일로 날짜 표현 |
| time | 시간 관련 모듈 ⬇️ |
| time.time() | 현재 시간을 초 단위로 반환 |
| time.localtime() | 현재 시간을 struct_time 객체로 반환 (연도,월,일,시,분,초 등 시각 정보 포함) |
| time.asctime() | struct_time 객체를 입력 받음 -> 문자열로 변환, 입력이 없으면 현재 시간을 문자열로 반환 |
| time.ctime() | time.time() 값을 입력으로 -> 문자열로 변환, 입력이 없으면 현재 시간을 문자열로 반환 |
| time.strftime() | 특정 포맷을 사용하여 시간을 문자열로 변환 |
| time.sleep() | 프로그램 실행을 주어진 시간동안 지연시킴 |
| random | 규칙이 없는 임의의 수(난수) 생성 모듈 ⬇️ |
| random.random() | 0-1 사이 난수 반환 |
| random.sample() | 시퀀드 데이터에서 지정된 개수만큼 랜덤한 값 반환 (중복 X) |
| random.choice() | 시퀀스 데이터에서 랜덤한 값 반환 |
| OS | OS 자원(환경변수, 디렉터리, 파일 등) 제어 모듈 ⬇️ |
| os.environ() | 환경변수를 딕셔너리 형태로 반환/접근 |
| os.chdir() | 현재 작업 중인 디렉터리 변경 |
| os.getcwd() | 현재 작업 중인 디렉터리의 절대경로 반환 |
| os.system() | 시스템 내 파일 반환 |
| os.popen() | 결과를 반환하는 파일 객체 반환 |
| os.mkdir() / os.rmdir() | 디렉터리 생성/삭제 |
| os.remove() | 파일 삭제 |
| os.rename() | 파일/디렉터리 이름 변경 |
| json | JSON 데이터를 쉽게 처리하고자 사용하는 모듈 |
{
"name": "홍길동",
"birth": "0525",
"age": 30
}
Key: Value 구조# 1_딕셔너리 자료형 -> JSON 형태로 (dump())
>>> import json
>>> data = {"name": "홍길동", "birth": "0525", "age": 30}
>>> with open('file.json', 'w') as f:
json.dump(data, f)
# 2_ 파이썬 자료형 -> JSON 문자열로
>>> import json
>>> data = {"name": "홍길동", "birth": "0525", "age": 30}
>>> json.data = json.dumps(data)
>>> json.data
'{"name": "홍길동", "birth": "0525", "age": 30}'
# 3_JSON 문자열 -> 딕셔너리 자료형으로
>>> json.loads(json.data)
{"name": "홍길동", "birth": "0525", "age": 30}
# 4_딕셔너리 외 다른 자료형 -> JSON 문자열로
>>> json.dumps([1, 2, 3])
'[1, 2, 3]'
>>> json.dumps((4, 5, 6))
'[4, 5, 6]'
# 5_출력 JSON 문자열 정렬
>>> data = {"name": "홍길동", "birth": "0525", "age": 30}
>>> print(json.dumps(data, indent=2, ensure_acii=False))
{
"name": "홍길동",
"birth": "0525",
"age": 30
}
# 6_아스키 형태의 문자열로 변경되는 것을 방지
>>> data = {"name": "홍길동", "birth": "0525", "age": 30}
>>> json_data = json.dumps(data, ensure_ascii=False)
>>> json_data
'{"name": "홍길동", "birth": "0525", "age": 30}'
>>> json.loads(json_data)
{"name": "홍길동", "birth": "0525", "age": 30}
수치 계산에 특화된 라이브러리
pip install numpy
import numpy as np
# 1차원 배열 생성
arr1 = np.array([1, 2, 3, 4])
print(arr1) # [1, 2, 3, 4]
# 2차원 배열 생성
arr2 = np.array([[1, 2], [3, 4]])
print(arr2) # [[1, 2]
# [3, 4]]
import numpy as np
# zeros()
zeros = np.zeros((2, 3))
print(zeros) # [[0. 0. 0.]
# [0. 0. 0.]]
# ones()
ones = np.ones((2, 3))
print(ones) # [[1. 1. 1.]
# [1. 1. 1.]]
import numpy as np
# arange()
sequence = np.arange(0, 10, 2)
print(sequence) # [0 2 4 6 8]
# linspace()
linspace = np.linspace(0, 1, 5)
print(linspace) # [0. 0.25 0.5 0.75 1.]
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) # shape: 배열의 크기(행, 열)
print(arr.ndim) # ndim: 배열의 차원
print(arr.size) # 배열의 총 원소 개수
print(arr.dtype) # 배열 원소의 데이터 타입
import numpy as np
# 1_인덱싱
# 1차원 배열
arr = np.array([10, 20, 30, 40])
print(arr[0])
print(arr[-1])
# 2차원 배열
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr[0, 1])
print(arr[1, -1])
# 2_슬라이싱
# 1차원 배열
arr = np.array([10, 20, 30, 40, 50])
print(arr[1:4])
print(arr[:3])
print(arr[::2])
# 2차원 배열
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr[:2, 1:])
print(arr[1:, :2])
import numpy as np
# 1_기본 연산
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
print(arr1 + arr2)
print(arr1 * arr2)
print(arr1 ** 2)
# 2_브로드캐스팅: 크기가 다른 배열 간 연산
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr + 10)
import numpy as np
# reshape()
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped = np.reshape(2, 3)
print(reshaped) # [[1 2 3]
# [4 5 6]]
# flatten()
arr = np.array([[1, 2, 3], [4, 5, 6]])
flattened = np.flatten()
print(flattened) # [1 2 3 4 5 6]
import numpy as np
# 1_filter
arr = np.array([1, 2, 3, 4, 5])
filtered = arr[arr > 3]
print(filtered) # [4 5]
# 2_random
random = np.random.rand(5)
random_int = np.random.randint(1, 20, size=(2, 3))
# 가중치 벡터
weights = np.array([0.5, -0.2])
# 가중치와 데이터의 내적
outputs = np.dot(data, weights)
# 시그모이드 함수
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 내적 결과에 시그모이드 적용
sigmoid_outputs = sigmoid(outputs)
# 초기 가중치 생성 (난수)
inital_weight = np.random.rand(2)
# 데이터 섞기
shuffled = np.random.permutation(len(data))
shuffled_data = data[shuffled_indices]
shuffled_labels = labels[shuffled_indices]
# 입력 데이터
input_data = np.array([[1.0, 2.0], [0.5, 1.5]])
# 첫 번째 층 가중치와 바이어스
weights_layer1 = np.array([[0.2, 0.4], [-0.5, 0.3]])
bias_layer1 = np.array([0.1, -0.2])
# 두 번째 층 가중치와 바이어스
weights_layer2 = np.array([[0.6], [0.1]])
bias_layer2 = np.array([0.3])
# 첫 번째 층 출력
layer1_output = sigmoid(np.dot(input_data, weights_layer1) + bias_layer1)
# 두 번째 층 출력
layer2_output = sigmoid(np.dot(layer1_output, weights_layer2) + bias_layer2)
# 예측 값
predictions = np.array([0.9, 0.4, 0.3])
# 실제 값
true_value = np.array([1, 0, 0])
# MSE 계산
mse = np.mean((predictions - true_value) ** 2)
reshaped_data = data.reshape(-1, 2)
데이터 분석과 조작에 특화된 라이브러리
pip install pandas
s = pd.Series([10, 20, 30], index=['A', 'B', 'C'])
data = {
'name': ['son', 'kang', 'han'],
'age': [30, 10, 20]
}
df = pd.DataFrame(data)
print(df)
df.head(2) # 상위 몇 개의 행 출력
df.tail(2) # 하위 몇 개의 행 출력
print(df.shape) # 데이터 크기 확인 (행, 열 개수)
print(df.info()) # 데이터 타입 및 결측 값 확인
print(df.describe() # 수치형 데이터의 요약 통계
# 단일 열 선택
print(df['Name'])
# 여러 열 선택
print(df['Name', 'Score'])
# loc
print(df.loc[0])
print(df.loc[:, 'Name']) # 모든 행에서 Name 열만 출력
# iloc
print(df.iloc[1])
print(df.iloc[:, 1]) # 모든 행에서 두 번째 열만 출력
high_scores = df[df['Score'] >= 90]
# 열 추가
df['Passed'] = df['Score'] >= 90
# 행 추가: concat()
new_data = {
'name': 'beak',
'age': 28
}
new = pd.DataFrame([new_data])
df = pd.concat([df, new], ignore_index=True)
# 특정 값 수정
df.loc[0, 'Score'] = 95
# 열 전체 수정
df['Passed'] = df['Score'] >= 90
# 결측 값 생성
df.loc[1, 'Score'] = None
# 결측 값 채우기
df['Score'] = df['Score'].fillna(0)
# 결측 값 제거
df = df.dropna()
# 오름차순 정렬
sorted_df = df.sort_values(by='Score')
# 내림차순 정렬
sorted_df = df.sort_values(by='Score', acending=False)
# 데이터 생성
data = {
'team': ['A', 'A', 'B', 'B'],
'score': [90, 85, 95, 88]
}
df = pd.DataFrame(data)
grouped = df.groupby('team')['score'].mean() # 팀별 평균 점수 계산
# 데이터 저장 (CSV 파일로)
df.to_csv('output.csv', index=False)