파이썬 데이터 분석 절차

2025. 2. 23. 11:14IT/AI

반응형

파이썬을 활용한 데이터 분석은 데이터 수집데이터 전처리탐색적 데이터 분석(EDA)모델링 및 분석시각화 및 인사이트 도출의 과정을 거칩니다. 



데이터 수집 (Data Collection)

1. 데이터 수집 방법
  • CSV, Excel, JSON, SQL 데이터베이스 등에서 불러오기
  • 웹 크롤링 또는 API 활용
  • 실시간 센서 및 로그 데이터 수집

2.  주요 라이브러리

import pandas as pd  # 데이터 처리
import requests  # API 호출
from sqlalchemy import create_engine  # DB 연결


3.  데이터 불러오기 예제

# CSV 파일 불러오기
df_csv = pd.read_csv("data.csv")

# Excel 파일 불러오기
df_excel = pd.read_excel("data.xlsx")

# JSON 데이터 불러오기
df_json = pd.read_json("data.json")

# SQL 데이터베이스에서 데이터 가져오기
engine = create_engine("mysql+pymysql://user:password@host/db_name")
df_sql = pd.read_sql("SELECT * FROM table_name", con=engine)

# API를 활용한 데이터 수집
response = requests.get("https://api.example.com/data")
df_api = pd.DataFrame(response.json())


데이터 전처리 (Data Preprocessing)


1.  데이터 확인

df_csv.info()          # 데이터 구조 및 타입 확인
df_csv.describe()      # 기초 통계량 확인
df_csv.head()          # 상위 5개 데이터 확인
df_csv.isnull().sum()  # 결측치 확인

2. 데이터 정제

# 결측치 처리 (NaN 값 채우기)
df_csv.fillna(df_csv.mean(), inplace=True)  # 평균값으로 채우기
df_csv.dropna(inplace=True)  # 결측치가 있는 행 제거

# 이상치 처리 (IQR 활용)
Q1 = df_csv["column"].quantile(0.25)
Q3 = df_csv["column"].quantile(0.75)
IQR = Q3 - Q1
df_clean = df_csv[(df_csv["column"] >= Q1 - 1.5 * IQR) & (df_csv["column"] <= Q3 + 1.5 * IQR)]

# 중복값 제거
df_csv.drop_duplicates(inplace=True)

# 데이터 타입 변환
df_csv["date_column"] = pd.to_datetime(df_csv["date_column"])  # 날짜형 변환
df_csv["category_column"] = df_csv["category_column"].astype("category")  # 범주형 변환


탐색적 데이터 분석 (EDA, Exploratory Data Analysis)

1. 데이터 분포 확인

import matplotlib.pyplot as plt
import seaborn as sns

# 히스토그램으로 데이터 분포 확인
sns.histplot(df_csv["column"], bins=30)
plt.show()

# 상관관계 분석
sns.heatmap(df_csv.corr(), annot=True, cmap="coolwarm")
plt.show()

2. 범주형 데이터 시각화

# 막대그래프 (카테고리별 개수)
sns.countplot(x="category_column", data=df_csv)
plt.show()

3. 변수 간 관계 분석

# 산점도 그래프
sns.scatterplot(x="feature1", y="feature2", data=df_csv)
plt.show()

4. 데이터 변환 및 특성 엔지니어링 (Feature Engineering)
  • 데이터 스케일링

from sklearn.preprocessing import StandardScaler, MinMaxScaler

scaler = StandardScaler()  # 표준화
df_csv[["feature1", "feature2"]] = scaler.fit_transform(df_csv[["feature1", "feature2"]])

  • 원-핫 인코딩 (범주형 데이터 변환)

df_encoded = pd.get_dummies(df_csv, columns=["category_column"])

  • 데이터 분할 (학습 / 테스트 세트)

from sklearn.model_selection import train_test_split

X = df_csv.drop("target_column", axis=1)  # 독립 변수
y = df_csv["target_column"]  # 종속 변수

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

 


반응형

모델링 및 분석


1. 머신러닝 모델 학습

from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

# 모델 학습
model = LinearRegression()
model.fit(X_train, y_train)

# 예측
y_pred = model.predict(X_test)

# 성능 평가
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error: {mse}")

2. 분류 모델 예제

from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

model = RandomForestClassifier()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")

결과 시각화 및 인사이트 도출


1. 실제값 vs 예측값 비교

plt.scatter(y_test, y_pred)
plt.xlabel("Actual Values")
plt.ylabel("Predicted Values")
plt.title("Actual vs Predicted")
plt.show()


2. 모델 성능 평가

from sklearn.metrics import classification_report

print(classification_report(y_test, y_pred))


보고서 작성 및 활용

1. 결과 정리
  • 데이터 전처리 과정 설명 (결측치 처리, 이상치 제거)
  • 변수 간 관계 분석 결과
  • 모델 학습 및 성능 평가 결과
  • 인사이트 도출 (비즈니스 적용 방안)
  
2. 저장 및 배포

df_csv.to_csv("cleaned_data.csv", index=False)  # 정제된 데이터 저장
import joblib
joblib.dump(model, "trained_model.pkl")  # 학습된 모델 저장

관련 블로그

 

데이터 분석 시 결측치(missing value) 처리

데이터 분석에서 결측치(missing value) 처리는 분석 결과의 신뢰성과 정확성에 영향을 미치므로 신중하게 접근해야 합니다. 일반적인 결측치 처리 방법은 다음과 같습니다.결측치 확인  • isnull().

make2t.tistory.com

 

반응형