TIL(Today I Learned)

[2024/12/27]내일배움캠프 QA/QC 1기 - 9일차

essay2892 2024. 12. 27. 20:07

데이터 분석 파이썬 종합반 5주차

알면 유용한 파이썬 문법들!

파일 불러오기, 패키지(라이브러리), 포맷팅(formatting), 리스트 캄프리헨션, lambda, glob, os, split, 클래스, 불리언 인덱싱, 데코레이션, 파이썬 에러 대처

import pandas as pd

df = pd.read_확장자('파일명')

코랩의 경우 드라이브 마운트 진행해야함

더보기
import pandas as pd

data = {
    'Name': ['John', 'Emily', 'Michael'],
    'Age': [30, 25, 35],
    'City': ['New York', 'Los Angeles', 'Chicago']
}

df = pd.DataFrame(data)
excel_file_path = '/content/sample_data/data.csv'
df.to_csv(excel_file_path, index = False)

print("csv 파일이 생성되었습니다.")

 

import pandas as pd

data = {
    'Name': ['John', 'Emily', 'Michael'],
    'Age': [30, 25, 35],
    'City': ['New York', 'Los Angeles', 'Chicago']
}

df = pd.DataFrame(data)
excel_file_path = '/content/sample_data/data.xlsx'
df.to_excel(excel_file_path, index = False)

print("Excel 파일이 생성되었습니다.")
import json

data = {
    'Name': ['John', 'Emily', 'Michael'],
    'Age': [30, 25, 35],
    'City': ['New York', 'Los Angeles', 'Chicago']
}

json_file_path = '/content/sample_data/data.json'

# json 파일을 쓰기모드로 열어서 data를 거기에 덮어씌우게 됩니다.
with open(json_file_path, 'w') as jsonfile:
    json.dump(data, jsonfile, indent=4)

print("JSON 파일이 생성되었습니다.")
 
data = {
    'Name': ['John', 'Emily', 'Michael'],
    'Age': [30, 25, 35],
    'City': ['New York', 'Los Angeles', 'Chicago']
}

text_file_path = '/content/sample_data/data.txt'

with open(text_file_path, 'w') as textfile:
    for key, item in data.items():
        textfile.write(str(key) + " : " + str(item) + '\n')

print("텍스트 파일이 생성되었습니다.")
더보기

pandas : 데이터 조작과 분석을 위한 라이브러리, 데이터를 효과적으로 조작하고 분석할 수 있도록 도와줌

numpy : 과학적 계산을 위한 핵심 라이브러리, 다차원 배열과 행렬 연산을 지원

matplotlib : 데이터 시각화를 위한 라이브러리

seaborn : Matplotlib을 기반으로 한 통계용 데이터 시각화 라이브러리, 보다 간편하고 아름다운 시각화

scikit-learn : 머신 러닝 알고리즘을 사용할 수 있는 라이브러리

statsmodels : 통계 분석을 위한 라이브러리

scipy : 과학기술 및 수학적인 연산을 위한 라이브러리, 다양한 과학 및 공학 분야에서 활용

tensorflow : 딥러닝 및 기계 학습을 위한 오픈소스 라이브러리, 구글에서 개발. 그래프 기반의 계산을 통해 수치 계산을 수행, 신경망을 구축하고 학습

pytorch : 딥러닝을 위한 오픈소스 라이브러리, Facebook에서 개발. 동적 계산 그래프를 사용하여 신경망을 구축하고 학습

 
import pandas as pd
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import seaborn
더보기

f-string ----- 추천

x = 10
print(f"변수 x의 값은 {x}입니다.")

 

옛날 방식

x = 10
print("변수 x의 값은 {}입니다.".format(x))
x = 10
print("변수 x의 값은 %d입니다." % (x)) ---- 비추천
 
더보기

리스트를 간결하게 생성하는 방법

반복문, 조건문을 사용하여 리스트를 생성할 때 사용

간결하고 가독성 좋은 방법

# 기본적인 구조
[표현식 for 항목 in iterable if 조건문]

 

# 예시: 1부터 10까지의 숫자를 제곱한 리스트 생성
squares = [x**2 for x in range(1, 11)]
print(squares)  # 출력: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 

# 예시: 리스트에서 짝수만 선택하여 제곱한 리스트 생성
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(even_squares)  # 출력: [4, 16, 36, 64, 100]

 

# 예시: 문자열 리스트에서 각 문자열의 길이를 저장한 리스트 생성
words = ["apple", "banana", "grape", "orange"]
word_lengths = [len(word) for word in words]
print(word_lengths)  # 출력: [5, 6, 5, 6]

# 예시: 리스트 컴프리헨션을 중첩하여 2차원 리스트 생성
matrix = [[i for i in range(1, 4)] for j in range(3)]
print(matrix)  # 출력: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
더보기

람다 함수(lambda function)는 익명 함수, 이름 없이 정의되는 간단한 함수

주로 한줄로 표현, def 키워드를 사용하지 않고 lambda 키워드를 사용하여 정의

함수를 매개변수로 전달하는 함수형 프로그래밍에서 유용하게 활용

간결성, 익명성, 함수형 프로그래밍, 가독성 등 유용

과도하게 사용하면 좋지 않음. 그러나 데이터 분석 관점에서는 간단한 수식 사용시 유용하므로 알아두기

 

add = lambda x, y: x + y
print(add(3, 5))  # 출력: 8

 

square = lambda x: x ** 2
print(square(4))  # 출력: 16

 

* filter(조건 함수, 반복 가능한 데이터) : 조건 충족하는 데이터만 추출할 때 사용

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # 출력: [2, 4, 6, 8, 10]

 

* map(함수, 반복 가능한 데이터) : 여러개의 값을 받아 각각의 값에 함수를 적용한 결과를 반환

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers)  # 출력: [1, 4, 9, 16, 25]
더보기

파일 시스템에서 파일을 찾을 때 사용되는 유용한 도구

주로 파일 이름이나 확장자에 따라 파일을 필터링하는 데 사용

폴더를 구분할때는 ‘/’기호를 사용

반드시 확장자도 함께 입력

 

import glob

# 현재 경로의 모든 파일을 찾기
file_list1 = glob.glob('*')

# 단일 파일 패턴으로 파일을 찾기
file_list2 = glob.glob('drive')

# 디렉토리 안의 모든 파일 찾기
file_list3 = glob.glob('sample_data/*')

# 특정 확장자를 가진 파일만 찾기
file_list4 = glob.glob('sample_data/*.csv')
더보기

운영 체제와 상호 작용하기 위한 다양한 함수들을 제공

파일 시스템 관리, 디렉토리 탐색, 파일 조작에 사용

파일 및 디렉토리 관리, 경로 관리, 환경 변수 관리, 실행 관리

 

# 현재 작업 디렉토리 가져오기
import os
cwd = os.getcwd()
print(cwd)

# 디렉토리 생성
import os
os.mkdir('sample_data/new_directory')

# 파일 이름 변경
import os
os.rename('sample_data/new_directory', 'sample_data/new_directory2')

# 파일 삭제
import os
os.remove(file_adress)

import os
os.remove('sample_data/data.csv')

# 경로 가져오기
import os
files = os.listdir('/content')
print(files)

# 경로 조작
import os
path = os.path.join('/content', 'sample_data', 'mnist_test.csv')
print(path)
더보기

문자열을 여러개로 쪼개는데 유용

 

sentence = "Hello, how are you doing today?"
words = sentence.split()
print(words)  # 출력: ['Hello,', 'how', 'are', 'you', 'doing', 'today?']

data = "apple,banana,grape,orange"
fruits = data.split(',')
print(fruits)  # 출력: ['apple', 'banana', 'grape', 'orange']

words = ['Hello,', 'how', 'are', 'you', 'doing', 'today?']
sentence = ' '.join(words)
print(sentence)  # 출력: Hello, how are you doing today?

fruits = ['apple', 'banana', 'grape', 'orange']
data = ','.join(fruits)
print(data)  # 출력: apple,banana,grape,orange

text = """First line
Second line
Third line"""
lines = text.split('\n')
print(lines)  # 출력: ['First line', 'Second line', 'Third line']

sentence = "Hello, how are you doing today?"
words = sentence.split()
first_three_words = words[:3]
print(first_three_words)  # 출력: ['Hello,', 'how', 'are']

text = "   Hello   how   are   you   "
cleaned_text = text.strip()
words = cleaned_text.split()
print(words)  # 출력: ['Hello', 'how', 'are', 'you']

# 데이터의 경로를 문자열로 표현
file_path = "/usr/local/data/sample.txt"

# split() 함수를 사용하여 디렉토리와 파일명으로 분할
directory, filename = file_path.rsplit('/', 1)
print("디렉토리:", directory)  # 출력: 디렉토리: /usr/local/data
print("파일명:", filename)    # 출력: 파일명: sample.txt
더보기

객체 지향 프로그래밍(OOP)의 중요한 개념

객체 지향 프로그래밍은 현실 세계의 사물을 모델링하여 프로그래밍하는 방법으로, 이를 통해 코드의 재사용성과 유지보수성을 향상

데이터와 해당 데이터를 처리하는 메서드(함수)를 함께 묶어놓은 것

데이터 구조화, 데이터 전처리 모듈화, 모델링과 분석 등에 사용 

메서드 : 클래스 내부에 정의된 함수. 특정 작업을 수행하거나 클래스의 상태를 변경하는 역할

속성 : 클래스나 클래스의 인스턴스에 속한 변수. 클래스나 인스턴스의 상태를 나타냄. 즉, 객체의 데이터를 저장

 

# 기본 구조
class ClassName:
    def __init__(self, parameter1, parameter2):
        self.attribute1 = parameter1
        self.attribute2 = parameter2

    def method1(self, parameter1, parameter2):
    # 메서드 내용 작성
        pass

 

__init__ 메서드는 클래스의 생성자(필수)로, 객체가 생성될 때 호출되며 초기화 작업을 수행

메서드의 첫 번째 매개변수로 self 반드시 사용

 

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# 객체 생성
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)

 

class Animal:
    def sound(self):
        print("Some generic sound")

class Dog(Animal):
    def sound(self):
        print("Woof")

class Cat(Animal):
    def sound(self):
        print("Meow")

# 다형성 활용
animals = [Dog(), Cat()]
for animal in animals:
    animal.sound()

 

class Car:
    def __init__(self, brand):
        self.brand = brand
   
    def start_engine(self):
        print(f"{self.brand}의 엔진을 가동합니다.")

# Car 클래스의 인스턴스 생성
my_car = Car("Toyota")
# start_engine() 메서드 호출
my_car.start_engine()  # 출력: Toyota의 엔진을 가동합니다.

 

class Dog:

    def __init__(self, name):
        self.name = name  # 인스턴스 속성

# Dog 클래스의 인스턴스 생성
my_dog = Dog("Buddy")
print(my_dog.name)      # 출력: Buddy

 

class Stock:
    def __init__(self, symbol, price, volume):
        self.symbol = symbol
        self.price = price
        self.volume = volume

# 객체 생성
stock1 = Stock("AAPL", 150.25, 100000)
stock2 = Stock("GOOG", 2800.75, 50000)

raw_data = [1,2,4,5,6,87,2,253654]

class DataPreprocessor:
    def __init__(self, data):
        self.data = data

    def normalize_data(self):
        # 데이터 정규화 작업 수행
        pass

    def handle_missing_values(self):
        # 결측치 처리 작업 수행
        pass

    def remove_outliers(self):
        # 이상치 제거 작업 수행
        pass

# 데이터 전처리 객체 생성
preprocessor = DataPreprocessor(raw_data)
preprocessor.normalize_data()
preprocessor.handle_missing_values()
preprocessor.remove_outliers()

class LinearRegressionModel:
    def __init__(self, data):
        self.data = data

    def train(self):
        # 선형 회귀 모델 학습
        pass

    def predict(self, new_data):
        # 새로운 데이터에 대한 예측 수행
        pass

    def evaluate(self):
        # 모델 평가 수행
        pass

# 선형 회귀 모델 객체 생성
lr_model = LinearRegressionModel(training_data)
lr_model.train()
predictions = lr_model.predict(new_data)
evaluation_result = lr_model.evaluate()
더보기

조건에 따라 요소를 선택하는 방법

NumPy를 사용하여 불리언 인덱싱을 수행, Pandas에서 데이터를 조건에 맞게 선택할 때 많이 사용

 

import numpy as np

# 배열 생성
arr = np.array([1, 2, 3, 4, 5])

# 불리언 배열 생성 (조건에 따라 True 또는 False 값을 갖는 배열)
condition = np.array([True, False, True, False, True])

# 불리언 인덱싱을 사용하여 조건에 맞는 요소 선택
result = arr[condition]

# 결과 출력
print("Result using boolean indexing:", result)  # 출력: [1 3 5]

# 불리언 인덱싱을 사용하여 배열에서 짝수인 요소만 선택
evens = arr[arr % 2 == 0]

# 결과 출력
print("Even numbers using boolean indexing:", evens)  # 출력: [2 4]
더보기

기존의 함수를 따로 수정하지 않고도 추가 기능을 넣고 싶을 때 사용(거의 사용하지 않음)

 

def decorator_function(original_function):
    def wrapper_function(**kwargs):
        # 함수 호출 전에 실행되는 코드
        result = original_function(**kwargs)
        # 함수 호출 후에 실행되는 코드
        return result
    return wrapper_function

 

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
 
import tensorflow as tf

@tf.function  # The decorator converts `add` into a `Function`.
def add(a, b):
  return a + b

add(tf.ones([2, 2]), tf.ones([2, 2]))  #  [[2., 2.], [2., 2.]]


import timeit
conv_layer = tf.keras.layers.Conv2D(100, 3)

@tf.function
def conv_fn(image):
  return conv_layer(image)

image = tf.zeros([1, 200, 200, 100])

print("Eager conv:", timeit.timeit(lambda: conv_layer(image), number=10))
print("Function conv:", timeit.timeit(lambda: conv_fn(image), number=10))
print("Note how there's not much difference in performance for convolutions")
더보기

구문 오류

print("Hello World'

 

SyntaxError: EOL while scanning string literal
 
들여쓰기 오류
def my_function():
print("Hello World!")
 
IndentationError: expected an indented block

 

이름 오류

# 위에 my_variable에 대한 변수에 대해 따로 언급한 것이 없는 상황
print(my_variable)

NameError: name 'my_variable' is not defined

 

타입 오류

result = "10" + 20
 
TypeError: can only concatenate str (not "int") to str

 

인덱스 오류

my_list = [1, 2, 3]
print(my_list[3])
 
IndexError: list index out of range

 

키 오류

my_dict = {"a": 1, "b": 2}
print(my_dict["c"])

KeyError: 'c'

 

파일을 찾을 수 없음

with open("nonexistent_file.txt", "r") as file:
    contents = file.read()
 
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent_file.txt'

 

위키독스 초보자를 위한 파이썬 300제

150 ~ 210

 

프로그래머스 기초문제 연습

 

개인 과제 다시 풀어보기