본문 바로가기
데이터 분석 관련

[패스트캠퍼스] 데이터분석 강의 학습일지 (3)

by 달빛 정원 2023. 4. 25.
반응형

파이썬과 친해지기 위해 기초지식을 습득하고 연습문제를 풀어보며 익숙해지는 중입니다. 국비지원 "빅데이터 분석 첫걸음"강의를 듣고 배운 내용을 정리하였습니다. 본 내용은 학습일지 1,2에 이어 작성합니다.

2023.04.17 - [데이터 분석 관련] - [패스트캠퍼스] 데이터분석 강의 학습일지

2023.04.24 - [데이터 분석 관련] - [패스트캠퍼스] 데이터분석 강의 학습일지 (2)

데이터분석 실습

파이썬 기초와 데이터 분석 2

이번 학습일지에서는 함수, I/O, class에 대한 개념을 배웠습니다. 이러한 부분은 데이터 분석에 있어 매우 기초적인 부분이라 잘 익혀놔야 할 것입니다.

함수(Function)

함수는 특정 기능을 구현하기 위해 만들어 놓은 코드의 모음으로 볼 수 있습니다. 함수는 임의의 input이 입력되었을때 내부적인 명령들(function)에 의해 output이 나오는 구조입니다. def를 앞에 쓰는데 뜻은 definition, 즉 정의라는 뜻입니다. 함수로 필요한 기능을 잘 셋팅해놓으면 재사용하기 쉽기 때문에 파이썬에서 매우 중요하게 다뤄지는 부분입니다.

함수는 def 함수이름 (parameter1, parameter2...): 로 정의 됩니다. 예를들어 사칙연산을 하는 함수를 만든다고 했을 때 다음과 같이 함수를 정의할 수 있습니다.

def calcul(a, b):
   result1 = a + b
   result2 = a - b
   result3 = a * b
   result4 = a / b
   return result1, result2, result3, result4
   
 calcul(10,2)
   
 (12, 8, 20, 5.0) #결과값

만약 파라미터 갯수가 정해지지 않았을 경우에는 *args를 사용하여 함수를 정의합니다.

def add_many(*args): # *(asterisk)를 앞에 붙이는 것으로 여러개의 parameter를 받아서 tuple로 변환하여 준다.   
  total = 0
  for arg in args:
   total += arg
  return total


print(add_many(1,2,3))
print(add_many(1,2,3,4,5,6,7,8))
print(add_many(5,6,7,8,9,0,8,7,7,6,6,5,55))

6
36
129

lambda함수라는 것은 한줄짜리 함수를 의미 합니다. 아래와 같이 매우 간단하게 함수를 정의할 수 있습니다.

def add(a, b):
  return a+b

# lambda 함수로 바꾸면?
f = lambda a, b : a + b
f(3,5)

8

이렇게 함수를 정의하여 쓸 수 있지만 사실 파이썬 내장 함수들도 여러개 있습니다. 예를 들어 sin, cos같은 수학을 쓸 수 있는 math함수 부터 난수를 입력하는 random함수까지 다양합니다. 필요할 때마다 검색하여 잘 사용할 수 있으면 될 듯 합니다. 이런 함수들을 활용하여 다양한 기능을 구현할 수 있습니다. 다음은 random함수를 활용한 복권번호 추출 함수 입니다. 

# 복권 숫자 추출 함수
import random

random.randint(1,45)
random.choices(list(range(1, 46)), k = 6)

I/O (Input/Output)

컴퓨터가 데이터를 입력받고 출력하는 작업을 의미합니다. input함수를 이용하여 직접 데이터를 입력할 수 있고 print함수를 이용하여 출력합니다. 또한 with open 함수를 활용하여 텍스트파일, 엑셀파일 등을 파이썬으로 불러와서 분석이 가능합니다. 다만 이러한 과정에서 데이터의 양, 컴퓨터의 사양에 따라 느려질 수 있는 단점도 있습니다(performance bottleneck).

파이썬에서는  standard in (stdin)은 무조건 문자열 타입으로 들어오기 때문에 int 등을 활용하여 다른 데이터 타입으로 바꾸어 사용해야 합니다.

list comprehension

데이터를 한개가 아닌 여러개 사용할 때 다음과 같은 방식으로 사용합니다. 

#2개로 가정한 경우
a, b = input().split(',')
a, b = int(a), int(b)

#for문을 사용한 코드
numbers = []
for num in input().split(','):
  numbers.append(int(num))
numbers

이를 좀 더 간략하고 간편하게 사용하는 방법이 list comprehension입니다 (위의 for문 기준).

[int(num) for num in input().split(",")]

File I/O

이 개념은 프로그램에서 파일을 저장하고 불러오는 것입니다. 파일은  txt, png, json, xlsx 등 다양하게 존재합니다. 텍스트 파일을 여는 방법은 read(), readline(), readlines(), for 문을 활용한 방법이 있습니다. 다음과 같은 코드의 형태로 파일을 열 수 있습니다.

여기서 'r', 'w', 'a'의 의미는 읽는 mode를 바꿔주는 것입니다. (r=read, w=write, a=append)

# f.read() 활용
file_path = "/000000/test.txt"
with open(file_path, 'r') as f:
  data = f.read()
data

# f.readline() 활용
with open(file_path, 'r') as f:
  data = f.readline()
data

# f.readlines() 활용
with open(file_path, 'r') as f:
  data = f.readlines()
data

#for문 활용
L = []
with open(file_path, 'r') as f:
  for line in f:
    L.append(line)
L

파일을 열어서 편집하고 다시 저장할 수도 있습니다. for문을 활용하여 한글자 이상인 텍스트를 리스트로 저장하고,  output 리스트 내용을 저장합니다.

output = []
# test.txt를 read mode로 열고 할 일이 끝나면 자동으로 닫는다.
with open(file_path, 'r') as f :
  data = f.readlines()

print(data)
# 한글자 이상인 텍스트만 output list에 저장한다.
for word in data:
  word = word.strip() # \n을 없애줌.
  if len(word)> 1:
    output.append(word)

print(output)

# result.txt로 output list에 있는 내용을 저장하기 위해 write mode로 열었다.

with open('result.txt', 'w') as f:
  #f.write()
  for word in output:
    print(word, file=f)

 

Class

클래스는 쉽게 말해 코드 템플릿입니다. 구현하려는 것을 객체(object)의 형태로 찍는다는 개념입니다. 구현하려는 대상의 특성을 class variable, 대상이 수행하는 일을 class method로 구현합니다. 생성자는 __init__함수를 활용하며 구현하려는 객체를 self라는 변수를 사용합니다. 예제에서는 노트북을 활용하여 클래스를 정의하고 구현하였습니다.

class Notebook: # 해당 노트북의 운영체제가 UNIX 계열 운영체제인지 아닌지 확인하는 Class Method를 구현

  def __init__(self, manufacturer, model,cpu_type, ram_size, ssd_size, os):
    self.manufacturer = manufacturer
    self.model = model
    self.cpu_type = cpu_type
    self.ram_size = ram_size
    self.ssd_size = ssd_size
    self.os = os

  ## TO-DO ##
  def is_UNIX(self):
    UNIX = ["macos", "Ubuntu", "ios", "android"]
    if self.os in UNIX:
      return True
    else:
      return False
  
nb = Notebook("Apple", "M1 max", "M1 max ", 64, 2048, "macos")
nb2 = Notebook("LG", "Gram 17", "Intel i7", 16, 512, "window")

#nb.is_UNIX()
nb2.is_UNIX()

노트북 모델을 출력해주는 class method를 구현하는 코드도 짜 봅니다.

class Notebook:

  def __init__(self, manufacturer, model,cpu_type, ram_size, ssd_size, os):
    self.manufacturer = manufacturer
    self.model = model
    self.cpu_type = cpu_type
    self.ram_size = ram_size
    self.ssd_size = ssd_size
    self.os = os

  ## TO-DO ##
  def is_UNIX(self):
    UNIX = ["macos", "Ubuntu", "ios", "android"]
    if self.os in UNIX:
      return True
    else:
      return False
    
  def print_model(self):
    print(f"This Notebook is {self.model} model.")

nb = Notebook("Apple", "M1 max", "M1 max ", 64, 2048, "macos")
nb2 = Notebook("LG", "Gram 17", "Intel i7", 16, 512, "window")

nb.print_model()  #This Notebook is M1 max model.
nb2.print_model() #This Notebook is Gram 17 model.

클래스 상속 (class inheritence)

# notebook class를 상속받아서 새로운 MacBook class를 정의
class Macbook(Notebook):
  def __init__(self,model, release_date, display_size, cpu_type, ram_size, ssd_size, os):
    self.model =  model
    self.release_date = release_date
    self.display_size = display_size
    self.cpu_type = cpu_type
    self.ram_size = ram_size
    self.ssd_size = ssd_size
    self.os = os
  
macbook = Macbook("Macbook Pro", "2020", "13", "Intel i5", 16, 1024, "macos")
macbook.print_model() # print_model 은 Notebook 클래스에서 상속받은 class method.

# notebook class를 상속받아서 새로운 Dell_Laptop class를 정의
class Dell_Laptop(Notebook):
  def __init__(self, model, series, display_size, cpu_type, ram_size, ssd_size, os="window 11"):
    self.model =  model
    self.series = series
    self.display_size = display_size
    self.cpu_type = cpu_type
    self.ram_size = ram_size
    self.ssd_size = ssd_size
    self.os = os
  
dell = Dell_Laptop("XPS", 9500, "Intel i7", 16, 2048, "Window 10")
dell.print_model()

Method Overriding

# 각 모델마다 다르게 정보를 출력해주는 is_UNIX 함수를 재정의합니다.
class Macbook(Notebook):
  def __init__(self,model, release_date, display_size, cpu_type, ram_size, ssd_size, os):
    self.model =  model
    self.release_date = release_date
    self.display_size = display_size
    self.cpu_type = cpu_type
    self.ram_size = ram_size
    self.ssd_size = ssd_size
    self.os = os

  def is_UNIX(self):
    UNIX = ["Ubuntu", "android", "Mojave", "Catelina", "Sierra", "High Sierra", "Montrery"]
    if self.os in UNIX:
      return True
    else:
      return False

class Dell_Laptop(Notebook):
  def __init__(self, model, series, display_size, cpu_type, ram_size, ssd_size, os="window 11"):
    self.model =  model
    self.series = series
    self.display_size = display_size
    self.cpu_type = cpu_type
    self.ram_size = ram_size
    self.ssd_size = ssd_size
    self.os = os
  
  def print_model(self):
    print(f"This notebook is {self.model} {self.series} {self.display_size} model.")

macbook = Macbook("Macbook Pro", "2020", "13", "Intel i5", 16, 1024, "Mojave")
macbook.is_UNIX()

dell = Dell_Laptop("XPS", 9500, "Intel i7", 16, 2048, "Window 10")
dell.print_model()
반응형

댓글