🐍 Python 🌿 중급

Python 데이터 분석

Pandas와 NumPy로 데이터 분석 마스터

⏱️ 8시간 👁️ 22 조회
📖 강좌 내용
# Python 데이터 분석 가이드

## 학습 목표
Pandas와 시각화 도구로 데이터를 분석합니다.

## 1. 필수 라이브러리
pip install pandas numpy matplotlib seaborn

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

## 2. 데이터 로드
CSV:
df = pd.read_csv("data.csv")
df = pd.read_csv("data.csv", encoding="utf-8")

Excel:
df = pd.read_excel("data.xlsx", sheet_name="Sheet1")

JSON:
df = pd.read_json("data.json")

SQL:
import sqlite3
conn = sqlite3.connect("db.sqlite")
df = pd.read_sql("SELECT * FROM users", conn)

## 3. 데이터 탐색
df.head() # 처음 5행
df.tail() # 마지막 5행
df.shape # (행, 열)
df.info() # 데이터 타입
df.describe() # 통계 요약
df.columns # 컬럼 목록
df.dtypes # 각 컬럼 타입

## 4. 데이터 선택
컬럼 선택:
df["name"]
df[["name", "age"]]

행 선택:
df.loc[0] # 인덱스로
df.loc[0:5] # 범위
df.iloc[0] # 위치로
df.iloc[0:5, 0:3] # 행, 열 범위

조건 선택:
df[df["age"] > 20]
df[(df["age"] > 20) & (df["city"] == "Seoul")]
df[df["name"].str.contains("Kim")]

## 5. 데이터 정제
결측치:
df.isna().sum() # 결측치 개수
df.dropna() # 결측치 행 제거
df.fillna(0) # 0으로 채우기
df.fillna(df.mean()) # 평균으로 채우기

중복:
df.duplicated().sum() # 중복 개수
df.drop_duplicates() # 중복 제거

타입 변환:
df["age"] = df["age"].astype(int)
df["date"] = pd.to_datetime(df["date"])

## 6. 데이터 변환
컬럼 추가:
df["total"] = df["price"] * df["qty"]

apply 함수:
df["grade"] = df["score"].apply(lambda x: "A" if x >= 90 else "B")

컬럼명 변경:
df.rename(columns={"old": "new"}, inplace=True)

정렬:
df.sort_values("age")
df.sort_values("age", ascending=False)
df.sort_values(["city", "age"])

## 7. 그룹화와 집계
df.groupby("city").mean()
df.groupby("city")["age"].mean()
df.groupby(["city", "gender"]).agg({
"age": "mean",
"salary": ["min", "max", "sum"]
})

피벗 테이블:
pd.pivot_table(df, values="sales", index="region", columns="month", aggfunc="sum")

## 8. 데이터 병합
concat:
pd.concat([df1, df2]) # 행 방향
pd.concat([df1, df2], axis=1) # 열 방향

merge (JOIN):
pd.merge(df1, df2, on="id")
pd.merge(df1, df2, left_on="user_id", right_on="id")
pd.merge(df1, df2, on="id", how="left") # left, right, outer, inner

## 9. Matplotlib 시각화
선 그래프:
plt.plot(x, y)
plt.title("Title")
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.show()

막대 그래프:
plt.bar(x, y)

산점도:
plt.scatter(x, y)

히스토그램:
plt.hist(df["age"], bins=10)

서브플롯:
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
axes[0].plot(x, y)
axes[1].bar(x, y)

## 10. Seaborn 시각화
히스토그램:
sns.histplot(df["age"])

박스플롯:
sns.boxplot(x="city", y="salary", data=df)

히트맵:
sns.heatmap(df.corr(), annot=True)

산점도:
sns.scatterplot(x="age", y="salary", hue="gender", data=df)

카운트플롯:
sns.countplot(x="city", data=df)

## 11. 데이터 저장
CSV:
df.to_csv("output.csv", index=False)
df.to_csv("output.csv", index=False, encoding="utf-8-sig")

Excel:
df.to_excel("output.xlsx", index=False)

JSON:
df.to_json("output.json", orient="records")

## 12. 실전 분석 흐름
1. 데이터 로드
2. 탐색적 분석 (EDA)
3. 데이터 정제
4. 변환 및 피처 생성
5. 시각화
6. 인사이트 도출
7. 결과 저장/공유

## 추천 학습 순서
1. Pandas 기본 문법
2. 데이터 정제
3. 그룹화와 집계
4. Matplotlib 시각화
5. Seaborn 고급 시각화