class="layout-aside-right paging-number">
본문 바로가기
데이터 분석/Python

Python(5) : 파이썬 문법

by heestory323 2025. 3. 11.

1. 파일 연산자, 불러오기 및 저장하기

2. 라이브러리 

3. 포맷팅(formating)

4. 리스트 컴프리헨션

5. lamda 함수

6. glob

7. os

8. split

9. class

10. builion

11.decoration

 

 

1. 파일 불러오기 및 저장

- 파일 확장자 :     .csv         .xls(x)          .json           .xtx .dat    

       데이터를      쉼표        표 형태      간단히 저장       텍스트

import pandas as pd
df = pd.read_확장자함수(파일이름)

 

- 불러오기

# 아래는 제가 데이터 파일을 넣은 구글 드라이브 경로에요!
# 제 구글 드라이브 안에 '스파르타코딩클럽_데이터분석을위한파이썬'이라는 폴더가 있는데
# 그 안에 파일을 넣은 상황 입니다.
# 여러분의 폴더 이름에 맞게 경로를 바꾸어 보세요!
# 경로는 폴더 오른쪽 마우스 
root = "/content/drive/MyDrive/스파르타코딩클럽_데이터분석을위한파이썬"
# 그리고 위 경로에 해당 파일 이름도 함께 이어 붙여서 파일 경로를 하나 완성합니다
file_address = root + "/ssec2403(통계표).xlsx"

# 위에서 지정해 놓은 파일 경로를 활용하여 불러오기만 하면 끝!
import pandas as pd
df = pd.read_excel(file_address)

 

2. 라이브러리

다양한 모듈(기능)들을 한 번에 모아놓은 것

# 아래와 같이 보통은 필요한 패키지를 한번에 다 불러온 다음 코딩을 진행합니다

import pandas as pd
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import seaborn
  • pandas : csv, xlsx, 표 형태
  • numpy : 과학적 계산을 위한 행열 연산
  • matplotlib : 데이터 시각화
  • seaborn : 아름다운 데이터 시각화
  • scikit-learn : 머신러닝
  • statsmodels : 통계 분석
  • scipy : 과학기술 및 수학 연산
  • tensorflow , pytorch : 딥러닝

 

3. 포맷팅(formating)

포맷팅 : 변수와 문자를 다양하게 출력할 때 쉽게 사용하도록 도와주는 문법  : 콤마(,) 안쓰도록 ! 

  • f-string     f "  { }  " 
    • 문자열 앞에 맨 앞에 f "  ~  {변수} ~ "  
x = 10
print("변수 x의 값은" , x , "입니다")
==
print(f"변수 x의 값은 {x}입니다.")

name = "Alice"
age = 25

print(f"이름: {name}, 나이: {age}세")

 

 

4. 리스트 컴프리헨션(List comprehension)

간결하게 가독성있게 리스트 만드는 방법 : 반복문 + 조건문

# 기본적인 구조
[표현식 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]


#일반 반복문
squares = []
for x in range (1,10+1) :
  squares.append(x**2)
 print(squares) # 출력: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 

5. lamda 함수

이름없이 간단하게 한 줄로 정의되는 함수

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

lamda 매개변수 : 함수가 작동하고픈 코드
add = lambda x, y: x + y  -- lamda라는 함수에 매개변수 x, y를 넣으면 x+y을 출력, 
print(add(3, 5))  # 출력: 8                            나온 그 값을 add에 담는다

 

  • 조건 함수로 lamda를 사용
    • 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]

 

6.  glob

 파일 찾을 때 사용되는 도구

import glob

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

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

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

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

 

7.  os

 운영체제(pc)와 관련 : 폴더 관리(생성, 삭제), 경로관리 등

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

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

 

8.  Split

문자열 쪼개기

 경로 / 기준으로 폴더명, 파일 구분하기

 

#특정 구분자를 기준으로 문자열을 분할하여 리스트로 변환하기

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

# 리스트의 각 항목을 문자열로 결합하기 (split 메서드는 아니지만 함께 알아두도록 해요!)

words = ['Hello,', 'how', 'are', 'you', 'doing', 'today?']
sentence = ' '.join(words)
print(sentence)  # 출력: Hello, how are you doing today?
# 여러 줄로 이루어진 문자열을 줄 단위로 분할하여 리스트로 변환하기
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']

 

  • rsplit() : 오른쪽에서 몇번째 문자까지 구분할꺼냐
# 데이터의 경로를 문자열로 표현
file_path = "/usr/local/data/sample.txt"

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

 

 

9. Class

클래스(Class) : 객체지향 프로그래밍 - 코드 재사용성, 유지보수성, 다형성(여기저기서 똑같이 사용 가능)

클래스로 이뤄진 함수 = 매서드(method)

class ClassName:
    def __init__(self, parameter1, parameter2):
        self.attribute1 = parameter1
        self.attribute2 = parameter2

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

초기값 정의 후 + 메서드 작성 - 메서드의 첫번째 매개변수는 반드시 self 

 

 

                     클래스(class)          vs           함수(function)

                                  코드 조직화, 재사용성 향상 

 데이터-데이터 처리 메서드(함수)를         특정작업을 수행하는 독립적인 코드블록
            함께 묶어 놓음 -> 효과적                  

                다향성 

 

10. 불리언 인덱싱(Boolean indexing) : T / F

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

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]

 

 

11. 데코레이션 

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

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()