Skip to content

Pandas 치트시트

파이썬의 데이터 분석 및 조작 라이브러리입니다.

01

시작하기

설치와 임포트

pandas는 관례상 pd로 임포트하며, 내부적으로 numpy 배열을 쓰므로 numpy는 np로 임포트합니다. 두 핵심 자료구조는 Series(1차원 레이블 배열)와 DataFrame(2차원 레이블 테이블)입니다. 파이썬의 거의 모든 테이블 데이터 조작이 여기서 시작합니다.

pandas
# Install pandas (pick one)
pip install pandas
conda install pandas

# Standard import convention
import pandas as pd
import numpy as np  # pandas relies heavily on numpy

# Check version
print(pd.__version__)

# Pandas is built on numpy: a Series is a 1D labeled array,
# a DataFrame is a 2D labeled table (dict of Series).

Series와 DataFrame

Series는 값의 단일 컬럼과 인덱스(레이블)를 갖습니다. DataFrame은 공통 인덱스를 공유하는 Series의 집합이며 스프레드시트나 SQL 테이블이라 생각하면 됩니다. dict(키=컬럼), 리스트의 리스트, numpy 배열, 파일로부터 DataFrame을 만들 수 있습니다.

pandas
import pandas as pd

# Series: 1D labeled array
s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"])
# a    10
# b    20
# ...

# DataFrame: 2D table (dict of columns)
df = pd.DataFrame({
    "name":  ["Alice", "Bob", "Charlie"],
    "age":   [25, 30, 35],
    "city":  ["NYC", "LA", "SF"],
})

# From list of lists with column names
df2 = pd.DataFrame([[1, 2], [3, 4]], columns=["a", "b"])

샘플 DataFrame 만들기

빠른 실험에는 dict로 작은 DataFrame을 만드세요. 더 큰 테스트에는 재현성을 위해 seed를 준 numpy 랜덤 생성기를 쓰세요. date_range는 시계열 작업의 기초인 DatetimeIndex를 만듭니다. 의미 있는 인덱스(날짜, ID)를 일찍 설정하면 이후의 선택과 조인이 훨씬 깔끔해집니다.

pandas
import pandas as pd
import numpy as np

# Quick test DataFrame with random data
df = pd.DataFrame({
    "id":     range(1, 6),
    "name":   ["Alice", "Bob", "Charlie", "David", "Eve"],
    "age":    [25, 30, 35, 28, 40],
    "score":  [85.5, 92.0, 78.3, 88.9, 95.2],
    "pass":   [True, True, False, True, True],
})

# Larger random DataFrame
rng = np.random.default_rng(42)
big = pd.DataFrame(rng.normal(size=(100, 4)), columns=list("ABCD"))

# Dates as index
dates = pd.date_range("2024-01-01", periods=5)
ts = pd.DataFrame({"value": [1, 2, 3, 4, 5]}, index=dates)

파일에서 데이터 읽기

read_csv가 주력입니다. 적재 후 정제를 피하려 관련될 때마다 sep, encoding, parse_dates, index_col을 항상 지정하세요. Parquet은 큰 데이터셋에서 CSV보다 훨씬 빠르고 작으며 dtype을 보존합니다. SQL에는 SQLAlchemy 엔진이 커넥션 풀링을 처리합니다. read_clipboard는 복붙 분석에 의외로 편리합니다.

pandas
import pandas as pd

# CSV — the most common
df = pd.read_csv("data.csv")
df = pd.read_csv("data.csv", sep=";", encoding="utf-8",
                 parse_dates=["date"], index_col="id")

# Excel (needs openpyxl)
df = pd.read_excel("data.xlsx", sheet_name="Sheet1")

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

# Parquet (fast columnar format, great for large data)
df = pd.read_parquet("data.parquet")

# SQL (needs SQLAlchemy)
from sqlalchemy import create_engine
engine = create_engine("sqlite:///my.db")
df = pd.read_sql("SELECT * FROM users", engine)

# Clipboard (paste a table from a spreadsheet)
df = pd.read_clipboard()

데이터 저장

인덱스가 의미 있는 데이터를 담지 않는 한 CSV/Excel 저장 시 항상 index=False를 전달하세요. 아니면 재로드 시 기생하는 'Unnamed: 0' 컬럼이 생깁니다. Parquet은 저장/로드 간 dtype을 보존합니다(CSV는 안 함). 기존 SQL 테이블에 행 추가는 if_exists='append', 덮어쓰기는 'replace'를 쓰세요.

pandas
import pandas as pd

# CSV (no index by default is usually what you want)
df.to_csv("output.csv", index=False)
df.to_csv("output.csv", index=False, encoding="utf-8-sig")  # Excel-friendly

# Excel (needs openpyxl)
df.to_excel("output.xlsx", sheet_name="Sheet1", index=False)

# Parquet (preserves dtypes, fast, compressed)
df.to_parquet("output.parquet")

# JSON
df.to_json("output.json", orient="records", indent=2)

# SQL
df.to_sql("users", engine, if_exists="replace", index=False)

# Multiple sheets to one Excel file
with pd.ExcelWriter("multi.xlsx") as writer:
    df1.to_excel(writer, sheet_name="sheet1", index=False)
    df2.to_excel(writer, sheet_name="sheet2", index=False)
02

데이터 검사

데이터 보기: head, tail, sample

head/tail은 가장자리를 보여 주고, sample은 무작위 행을 보여 주어 분포와 형식의 정상성 검사에 더 대표적입니다. 넓은 DataFrame을 검사할 때는 set_option으로 잘림을 끄세요. 기본값이 컬럼과 행을 숨깁니다. 어떤 분석이든 전에 샘플 데이터를 보면 인코딩 문제, 센티널 값, 타입 불일치를 일찍 잡습니다.

pandas
import pandas as pd

# First/last rows
df.head()        # first 5 (default)
df.head(10)      # first 10
df.tail()        # last 5
df.tail(3)       # last 3

# Random sample (great for sanity checks)
df.sample(5)                    # 5 random rows
df.sample(frac=0.1, random_state=42)  # 10% of rows
df.sample(n=5, replace=True)    # sample with replacement (bootstrap)

# See the raw values (not truncated)
pd.set_option("display.max_rows", 200)
pd.set_option("display.max_columns", None)
pd.set_option("display.width", 1000)

구조와 Dtype

info()가 단일 최유용 검사 호출입니다. dtype, 컬럼별 non-null 수, 메모리를 보여 줍니다. object dtype(보통 비효율 저장 문자열)에 주의하고, 'category'나 'string' dtype으로 변환하면 메모리를 아낍니다. memory_usage(deep=True)는 object 컬럼의 진짜 비용을 드러내며 보고된 것보다 훨씬 큰 경우가 많습니다.

pandas
# Shape and basic structure
df.shape         # (rows, cols)
df.size          # rows * cols
df.ndim          # 2 for DataFrame, 1 for Series
len(df)          # number of rows

# Column names and dtypes
df.columns       # column labels
df.index         # row labels
df.dtypes        # dtype of each column
df.info()        # concise summary: dtypes, non-null counts, memory

# Memory usage (helpful for big data)
df.memory_usage(deep=True)
df.info(memory_usage="deep")

기술 통계

describe()가 빠른 통계 요약을 줍니다. 어긋난 count(결측)와 의심스러운 min/max에 주의하세요. value_counts()는 범주형 컬럼에 필수입니다(빈도와 클래스 균형 표시). corr()의 기본은 Pearson이고 순위 상관은 method='spearman'입니다. 혼합 타입 프레임에서는 오류를 피하려 항상 numeric_only=True를 쓰세요.

pandas
# Numeric summary (count, mean, std, min, quartiles, max)
df.describe()
df.describe(include="all")   # include non-numeric too
df.describe(percentiles=[.1, .5, .9])

# Per-column stats
df["age"].mean()
df["age"].median()
df["age"].std()
df["age"].var()
df["age"].min(), df["age"].max()
df["age"].quantile(0.95)

# Non-numeric summaries
df["city"].value_counts()
df["city"].unique()
df["city"].nunique()

# Correlation and covariance
df.corr(numeric_only=True)
df.cov(numeric_only=True)

고유 값과 개수

value_counts가 가장 많이 쓰이는 pandas 메서드 중 하나입니다. 비율에는 normalize=True를, 결측 확인에는 dropna=False를 짝지으세요. crosstab은 두 범주형의 빈도표를 만들어 카이제곱 검정과 혼동 행렬에 유용합니다. value_counts 전에 연속 컬럼을 binning하면 분포 형태가 드러납니다.

pandas
# Unique values
df["city"].unique()              # array of unique values
df["city"].nunique()             # count of unique
df["city"].nunique(dropna=False) # include NaN

# Value counts (frequency table)
df["city"].value_counts()
df["city"].value_counts(normalize=True)   # proportions
df["city"].value_counts(ascending=True)
df["city"].value_counts(dropna=False)     # count NaN too

# Cross tabulation (frequency table of two columns)
pd.crosstab(df["city"], df["pass"])

# Binning then counting
df["age_group"] = pd.cut(df["age"], bins=[0, 18, 30, 50, 100],
                          labels=["child", "young", "adult", "senior"])
df["age_group"].value_counts()

결측값 확인

분석 전 항상 결측을 확인하세요. 컬럼별 isnull().sum()이 표준 첫 검토입니다. 결측 비율이 높은 컬럼은 드롭하거나 다른 처리 전략이 필요할 수 있습니다. 핵심 컬럼에 결측이 있는 행은 df[df.isnull().any(axis=1)]로 필터합니다. missingno 라이브러리가 결측 패턴을 시각화해 구조적 데이터 문제를 찾게 합니다.

pandas
# Count missing per column
df.isnull().sum()
df.isna().sum()           # alias

# Fraction missing
df.isnull().mean().mul(100).round(2)  # % missing per column

# Total missing
df.isnull().sum().sum()

# Rows with any missing
df[df.isnull().any(axis=1)]

# Non-null counts
df.notnull().sum()

# Visualize missingness pattern
# (requires missingno: import missingno as msno; msno.matrix(df))
03

Series 기본

Series 생성

Series는 레이블(인덱스)이 있는 1차원 배열입니다. 인덱스로 위치가 아니라 레이블로 값을 찾을 수 있습니다. 작은 dtype(int8, float32) 지정이 큰 데이터에서 메모리를 아낍니다. int8은 -128..127을 담아 불리언-정수나 작은 코드에 충분합니다. dict 키가 자연히 인덱스가 됩니다.

pandas
import pandas as pd
import numpy as np

# From a list
s = pd.Series([1, 2, 3, 4])

# From a list with custom index
s = pd.Series([10, 20, 30], index=["a", "b", "c"])

# From a dict (keys become index)
s = pd.Series({"a": 1, "b": 2, "c": 3})

# From a numpy array
s = pd.Series(np.random.randn(5))

# Scalar broadcast to an index
s = pd.Series(5, index=["a", "b", "c"])  # [5, 5, 5]

# Specify dtype
s = pd.Series([1, 2, 3], dtype="float64")
s = pd.Series([1, 2, 3], dtype="int8")    # save memory

인덱싱과 선택

레이블 기반 슬라이싱(s['a':'c'])은 양쪽 끝을 '포함'합니다. 배타적인 Python 위치 슬라이싱과의 흔한 차이입니다. 모호함을 피하려 레이블에는 .loc, 위치에는 .iloc을 쓰세요. 특히 정수 인덱스에서. 기본 s[...]는 중복 정의되어(dtype에 따라 레이블 또는 위치) 프로덕션 코드에서는 명시적 .loc/.iloc이 더 안전합니다.

pandas
s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"])

# By label (index)
s["a"]            # 10
s[["a", "c"]]     # multiple labels -> Series
s["a":"c"]        # slice INCLUSIVE of both ends (label-based)

# By position
s.iloc[0]         # first by position
s.iloc[-1]        # last
s.iloc[1:3]       # EXCLUSIVE of end (positional, like Python)

# By label with .loc (explicit)
s.loc["a"]
s.loc["a":"c"]    # inclusive

# Boolean indexing
s[s > 20]
s[(s > 10) & (s < 40)]

벡터화 연산

Series 연산은 벡터화되며(Python 루프 없음) 인덱스에 정렬됩니다. 두 Series를 더하면 pandas가 레이블을 매칭하고 겹치지 않는 곳에 NaN을 채웁니다. 이 인덱스 정렬이 pandas의 킬러 피처지만 놀랄 수 있습니다. 순수 위치 기반 산술을 원하면 .values로 원시 numpy 배열에 대해 연산하세요. 벡터화 연산은 iterrows 루프보다 100~1000배 빠릅니다.

pandas
s = pd.Series([1, 2, 3, 4])

# Element-wise arithmetic (aligns on index)
s + 10          # [11, 12, 13, 14]
s * 2
s ** 2
1 / s           # [1.0, 0.5, 0.333, 0.25]

# Between two Series (aligns on index, NaN for mismatches)
s1 = pd.Series({"a": 1, "b": 2, "c": 3})
s2 = pd.Series({"b": 20, "c": 30, "d": 40})
s1 + s2         # a=NaN, b=22, c=33, d=NaN

# Comparison and boolean
s > 2           # [False, False, True, True]
s.between(2, 3) # inclusive

# Math methods
s.sum(), s.mean(), s.std(), s.cumsum()

유용한 Series 메서드

sort_values와 rank가 일상 도구입니다. drop_duplicates는 기본적으로 첫 발생을 유지하며 마지막은 keep='last'입니다. clip은 플롯 전 이상값 상한 제한에 편리합니다. 대부분의 메서드는 기본적으로 NaN을 건너뛰며 NaN 전파는 skipna=False입니다. 많은 메서드가 새 Series를 반환하므로(pandas는 대체로 불변) 사슬로 잇세요: s.dropna().sort_values().head(10).

pandas
s = pd.Series([3, 1, 4, 1, 5, 9, 2, 6, np.nan])

# Sorting
s.sort_values()                  # ascending
s.sort_values(ascending=False)
s.sort_index()

# Ranking
s.rank(method="average")         # 'min','max','first','dense'

# Unique, counts
s.unique()
s.nunique()
s.value_counts()
s.duplicated()                   # boolean: True if seen before
s.drop_duplicates()

# Statistical
s.sum(), s.prod(), s.cumsum(), s.cummax()
s.abs()
s.round(2)
s.clip(lower=0, upper=10)        # cap values to a range
s.quantile([0.25, 0.5, 0.75])

Series의 NaN 처리

fillna의 전략이 많습니다. 상수, 통계량(mean/median), 전/후 방향 채우기(시계열에 좋음), 보간. ffill/bfill은 마지막 알려진 값을 전파하며 건너뛰면 안 되는 센서나 주식 데이터에 이상적입니다. 읽을 때 na_values로 센티널('?', -999)을 NaN으로 변환해 균일 처리하세요. interpolate는 linear, time, index 기반 메서드를 지원합니다.

pandas
s = pd.Series([1.0, 2.0, np.nan, 4.0, np.nan])

# Detect
s.isna()             # boolean mask
s.notna()
s.isna().sum()       # count of NaN

# Drop
s.dropna()           # remove NaN

# Fill
s.fillna(0)                       # constant
s.fillna(s.mean())                # with mean
s.fillna(method="ffill")          # forward fill (old API)
s.ffill()                         # forward fill (new)
s.bfill()                         # backward fill
s.interpolate()                   # linear interpolation

# Replace sentinel values with NaN on read
# pd.read_csv("x.csv", na_values=["?", "N/A", ""])
04

선택과 필터링

컬럼 선택

대괄호 표기 df['col']은 항상 동작합니다. 점 표기 df.col은 편리하지만 공백이 있는 이름이나 메서드와 충돌하는 이름('count' 등)에서 실패합니다. filter(like=)와 select_dtypes는 각 이름을 나열하지 않고 컬럼 그룹을 잡는 깔끔한 방법으로, 수백 컬럼의 넓은 DataFrame에서 귀중합니다.

pandas
# Single column (returns Series)
df["age"]
df.age            # only if name is a valid Python identifier

# Multiple columns (returns DataFrame)
df[["name", "age", "city"]]

# Columns by pattern
df.filter(like="age")               # columns containing "age"
df.filter(regex="^\d{4}$")          # columns matching regex
df.filter(items=["name", "age"])    # specific columns

# Select by dtype
df.select_dtypes(include="number")
df.select_dtypes(include=["int64", "float64"])
df.select_dtypes(exclude="object")
df.select_dtypes(include="datetime")

loc vs iloc

pandas 1위 함정: .loc은 레이블(포함 슬라이스), .iloc은 위치(배타 슬라이스)를 씁니다. 할당에는 항상 .loc/.iloc을 쓰세요. df[df.a<5]['b']=0 같은 체이닝 인덱싱은 SettingWithCopyWarning을 일으키고 조용히 실패할 수 있습니다. .loc은 (레이블 기반 필터링인) 불리언 마스크를 지원하며 필터와 할당의 깔끔한 방법입니다.

pandas
# .loc: label-based (inclusive slices)
df.loc[5]                         # row with index label 5
df.loc[5, "name"]                 # row 5, column 'name'
df.loc[5:10, ["name", "age"]]     # rows 5-10 (inclusive), 2 cols
df.loc[df["age"] > 30]            # boolean mask

# .iloc: position-based (exclusive slices)
df.iloc[0]                        # first row
df.iloc[-1]                       # last row
df.iloc[0:5]                      # first 5 rows (exclusive)
df.iloc[0:5, 0:2]                 # first 5 rows, first 2 cols
df.iloc[:, 0]                     # all rows, first column

# Setting values (use .loc for assignment!)
df.loc[df["age"] < 0, "age"] = 0  # cap negatives to 0

# AVOID chained indexing: df[df["a"]<5]["b"] = 0  # SettingWithCopyWarning

불리언 필터링

조건 결합 시 각 조건에 괄호를 치고 & | ~를 쓰세요. Python의 and/or는 불리언 배열에 동작하지 않습니다. isin이 여러 값 필터의 깔끔한 방법입니다(사슬 ==보다 빠름). 문자열 필터링은 .str 접근자를 쓰고, 부정은 ~(비트 NOT)입니다. 이들은 모두 새 필터된 DataFrame을 반환하므로 유지하려 변수에 할당하세요.

pandas
# Single condition
df[df["age"] > 30]
df[df["city"] == "NYC"]

# Multiple conditions (use & | ~, NOT and/or/not; parenthesize!)
df[(df["age"] > 25) & (df["city"] == "NYC")]
df[(df["city"] == "NYC") | (df["city"] == "LA")]
df[~df["pass"]]                       # NOT pass

# isin for membership
df[df["city"].isin(["NYC", "LA", "SF"])]

# String methods in filters
df[df["name"].str.startswith("A")]
df[df["name"].str.contains("li", case=False)]

# Between
df[df["age"].between(25, 35, inclusive="both")]

# Null checks
df[df["score"].isnull()]
df[df["score"].notnull()]

query() 메서드

query()는 SQL처럼 읽히며 불리언 인덱싱의 어디에나 괄호 요구를 피합니다. 지역 Python 변수 참조에는 @를 쓰세요. 큰 DataFrame에서 query가 더 빠를 수 있습니다. numexpr로 표현식을 평가해 중간 불리언 배열 생성을 피하기 때문입니다. groupby 사슬과 파이프라인 안에서 특히 좋습니다.

pandas
# query() — string-based filtering, often more readable
df.query("age > 30")
df.query("age > 25 and city == 'NYC'")
df.query("age > 25 and city in ['NYC', 'LA']")
df.query("age > 25 or score > 90")

# Refer to Python variables with @
cities = ["NYC", "LA"]
df.query("city in @cities")

# Compare columns
df.query("score > age")

# Negation
df.query("not pass")

# query is faster than boolean indexing on large frames
# because it uses numexpr to avoid intermediate arrays

샘플링과 가중치

sample(frac=0.8) 뒤의 drop(train.index)이 원본 인덱스를 유지하는 깔끔한 train/test 분할입니다. 계층 샘플링(클래스 비율 유지)에는 수동 pandas 코드보다 sklearn의 train_test_split이 더 신뢰할 만합니다. 가중치 샘플링은 중요도 샘플링이나 편향 데이터 시뮬레이션에 유용합니다.

pandas
# Random sample
df.sample(n=5)                          # 5 rows
df.sample(frac=0.1)                     # 10% of rows
df.sample(n=5, random_state=42)         # reproducible

# Sample with weights
df.sample(n=5, weights="score")         # higher score -> more likely

# Sample with replacement (bootstrap)
df.sample(n=len(df), replace=True)

# Train/test split
train = df.sample(frac=0.8, random_state=42)
test = df.drop(train.index)

# Stratified sample (preserve class proportions)
from sklearn.model_selection import train_test_split
train, test = train_test_split(df, test_size=0.2,
                                stratify=df["city"], random_state=42)
05

데이터 정제

결측 데이터 처리

dropna(how='all')는 완전히 빈 행만 드롭하고, thresh는 non-null이 N개 이상인 행을 유지합니다. 컬럼별 채움은 dict가 여러 fillna 호출보다 깔끔합니다. 시계열에는 ffill/bfill과 interpolate가 연속성을 보존합니다. 결측 자체가 정보인지 항상 고려하세요. 결측 대체 전 'is_missing' 지표 컬럼을 더하면 ML을 위해 신호가 보존됩니다.

pandas
# Drop rows with any missing
df.dropna()                       # any NaN in any column
df.dropna(how="all")              # only if ALL columns NaN
df.dropna(subset=["age", "city"]) # only check these columns
df.dropna(thresh=3)               # keep rows with >=3 non-NaN

# Fill missing
df.fillna(0)
df.fillna({"age": df["age"].mean(),
           "city": "Unknown"})
df["age"] = df["age"].fillna(df["age"].median())

# Forward/backward fill (for time series)
df.ffill()
df.bfill()

# Interpolate
df.interpolate(method="linear")
df.interpolate(method="time")     # for DatetimeIndex

# Flag rows that were imputed
df["age_was_missing"] = df["age"].isnull()

중복 제거

duplicated()가 이전 행을 반복하는 행을 표시하며, 첫 발생을 표시하려 keep='last'입니다. keep=False는 (첫 행 포함) 모든 중복 행을 표시해 충돌 행 전체를 검사할 때 유용합니다. drop_duplicates는 새 DataFrame을 반환하며 수정하려 inplace=True 또는 재할당합니다. subset으로 email이나 ID 같은 키 컬럼 기준 중복 제거가 됩니다.

pandas
# Find duplicates
df.duplicated()                   # True for rows that are duplicates of earlier
df.duplicated().sum()             # count
df[df.duplicated()]               # view duplicates

# Drop duplicates
df.drop_duplicates()              # full-row duplicates
df.drop_duplicates(subset=["email"])   # dup on email only
df.drop_duplicates(subset=["name", "dob"], keep="last")  # keep last occurrence
df.drop_duplicates(keep=False)    # drop ALL duplicates (keep none)

# Find rows where a column is duplicated
df[df.duplicated(subset=["email"], keep=False)]
# .keep=False marks ALL duplicates (including first)

이름 변경과 재배치

columns dict를 준 rename이 이름 변경의 가장 안전한 방법입니다. 나열된 컬럼만 바꾸고 나머지는 그대로 둡니다. 컬럼 재배치는 원하는 순서의 선택일 뿐입니다. 지저분한 인덱스 교체는 set_index 뒤 reset_index(drop=True)가 깔끔합니다. 컬럼 이름에는 일찍 str.strip을 쓰세요. 보이지 않는 후행 공백이 끝없는 'KeyError' 골칫거리를 만듭니다.

pandas
# Rename columns
df.rename(columns={"old_name": "new_name"})
df.rename(columns=str.upper)        # uppercase all
df.rename(columns=str.strip)        # strip whitespace

# Replace all column names
df.columns = ["id", "name", "age"]

# Add prefix/suffix
df.add_prefix("col_")
df.add_suffix("_v2")

# Reorder columns
df[["name", "age", "city"]]          # select in new order

# Reorder rows by index
df.sort_index()

# Reset / set index
df.reset_index(drop=True)            # drop old index
df.set_index("id")                   # use 'id' as index

# Swap rows and columns
df.transpose()  # or df.T

타입 변환

astype은 파싱 불가 값에서 실패하지만, errors='coerce'를 준 pd.to_numeric은 나쁜 값을 NaN으로 바꿔 지저분한 데이터에 훨씬 안전합니다. 'category' dtype은 저카디널리티 문자열에서 메모리를 크게 아낍니다. 다운캐스트(int64->int8)는 작은 값 범위의 컬럼에서 메모리를 8배 줄입니다. 속도와 정확성을 위해 날짜는 항상 명시적 형식 문자열로 파싱하세요.

pandas
# Convert a column's dtype
df["age"] = df["age"].astype(int)
df["price"] = df["price"].astype(float)
df["pass"] = df["pass"].astype(bool)
df["city"] = df["city"].astype("category")    # save memory

# Convert with pd.to_numeric (handles bad values)
df["price"] = pd.to_numeric(df["price"], errors="coerce")  # bad -> NaN
df["price"] = pd.to_numeric(df["price"], errors="ignore")  # leave as-is

# Parse dates
df["date"] = pd.to_datetime(df["date"], format="%Y-%m-%d")

# Convert multiple columns at once
df = df.astype({"age": "int8", "score": "float32", "city": "category"})

# Downcast to save memory
df["age"] = pd.to_numeric(df["age"], downcast="integer")

값 교체

replace가 분석 전 센티널 값(-999, '?')을 NaN으로 바꾸는 주력입니다. map은 dict 조회를 요소별 적용하며(매칭 안 되는 값은 NaN) where는 조건이 True인 값을 유지하고 나머지를 교체하며, mask는 그 반대입니다. 이들은 모두 새 객체를 반환하므로 적용하려 재할당하세요.

pandas
# Replace specific values
df["city"].replace({"NYC": "New York", "LA": "Los Angeles"})
df.replace(-999, np.nan)              # whole frame
df.replace(["?", "N/A", ""], np.nan)  # multiple sentinels

# Replace by condition (mask)
df.loc[df["age"] < 0, "age"] = np.nan

# Clip outliers
df["age"] = df["age"].clip(0, 120)

# Map values with a dict (like a lookup)
df["grade"] = df["score"].map({90: "A", 80: "B", 70: "C"})

# Where: keep where condition True, else replace
df["age"].where(df["age"] >= 0, 0)    # set negatives to 0

# Mask: opposite of where
df["age"].mask(df["age"] < 0, 0)
06

데이터 변환

apply와 applymap

apply는 요소/행마다 Python 함수를 실행합니다. 유연하지만 느립니다(벡터화 연산보다 100배). 가능하면 항상 벡터화 연산(df['col'] + 1, .str.upper())을 선호하세요. apply는 벡터화할 수 없는 로직(커스텀 문자열 파싱, 여러 컬럼을 참조하는 조건 변환)에 쓰세요. 행 단위 작업은 axis=1이며 row['col']로 컬럼에 접근합니다.

pandas
# Apply a function to each element of a column (Series)
df["age"] = df["age"].apply(lambda x: x + 1)
df["name"] = df["name"].apply(str.upper)

# Apply with multiple args
df["score"] = df["score"].apply(lambda x, n: round(x, n), n=2)

# Apply a function to each ROW (axis=1) — use columns
df["full"] = df.apply(lambda row: f"{row['name']} ({row['age']})", axis=1)

# Apply to every element of a DataFrame (newer: .map)
df = df.map(lambda x: str(x).strip() if isinstance(x, str) else x)

# Vectorized alternative (MUCH faster than apply)
df["age"] = df["age"] + 1  # vectorized, prefer this
df["name"] = df["name"].str.upper()

컬럼 추가와 수정

np.where가 벡터화된 if-else로 lambda를 준 apply보다 훨씬 빠릅니다. np.select가 case/when 문처럼 여러 조건을 처리합니다. assign이 사슬 친화적 컬럼 추가 방법입니다(파이프라인에서 좋음). insert가 특정 위치에 컬럼을 놓습니다. 컬럼 드롭은 drop(columns=[...])이 del df['col']보다 훨씬 명확합니다.

pandas
# Add a new column
df["full_name"] = df["first"] + " " + df["last"]
df["is_adult"] = df["age"] >= 18

# Conditional column with np.where
df["category"] = np.where(df["age"] >= 18, "adult", "minor")

# Multiple conditions with np.select
conditions = [df["age"] < 18, df["age"] < 65, df["age"] >= 65]
choices = ["minor", "adult", "senior"]
df["group"] = np.select(conditions, choices, default="unknown")

# insert at a specific position
df.insert(2, "score_pct", df["score"] / 100)  # at col index 2

# Assign multiple columns at once (returns new df)
df = df.assign(
    age_months=df["age"] * 12,
    score_squared=df["score"] ** 2,
)

# Drop columns
df.drop(columns=["temp", "junk"])

Binning과 이산화

cut은 범위를 등폭 bin으로 나누고(빈 bin이 생길 수 있음) qcut은 등빈도 bin으로 나눕니다(각 bin이 대략 같은 개수). 치우친 데이터에는 보통 qcut이 더 유용합니다. right=False가 (오른쪽 포함 (0,18] 대신) 왼쪽 포함 bin [0,18)을 만듭니다. binning된 컬럼은 범주형 dtype이 되어 groupby 집계에 완벽합니다.

pandas
# Equal-width bins
df["age_bin"] = pd.cut(df["age"], bins=4)

# Custom bins with labels
df["age_group"] = pd.cut(
    df["age"],
    bins=[0, 18, 30, 50, 100],
    labels=["child", "young", "adult", "senior"],
    right=False,  # left-inclusive: [0, 18)
)

# Equal-frequency bins (quantiles)
df["income_quartile"] = pd.qcut(df["income"], q=4, labels=["Q1","Q2","Q3","Q4"])

# Get bin edges
df["age_bin"].value_counts(sort=False)
pd.cut(df["age"], bins=4).cat.categories  # see the bin ranges

문자열 연산 (.str 접근자)

.str 접근자가 Python 문자열 메서드를 벡터화합니다. apply(str.upper)로 루프 돌리지 마세요. expand=True를 준 split이 한 컬럼을 여러 개로 만들며(이름 분할에 좋음) 이름 붙은 그룹의 extract가 텍스트에서 구조화 데이터를 뽑습니다. 모든 .str 메서드는 NaN 입력에 NaN을 반환하며 그 동작은 na=으로 제어합니다.

pandas
# All vectorized string methods via .str
df["name"] = df["name"].str.upper()
df["name"] = df["name"].str.lower()
df["name"] = df["name"].str.strip()           # remove leading/trailing
df["name"] = df["name"].str.replace(" ", "_")
df["name"] = df["name"].str.title()           # Title Case

# Split
df["name"].str.split(" ")                     # list per row
df[["first", "last"]] = df["name"].str.split(" ", expand=True)

# Contains / startswith / match (returns boolean)
df["name"].str.contains("li", case=False, na=False)
df["name"].str.startswith("A")
df["name"].str.match(r"^A\w+$")              # regex match

# Extract with regex groups
df["name"].str.extract(r"(?P<first>\w+)\s+(?P<last>\w+)")

# Length
df["name"].str.len()

날짜와 시간 (.dt 접근자)

날짜 컬럼은 먼저 pd.to_datetime으로 변환한 뒤 .dt로 구성 요소에 접근하세요. .dt 접근자가 year/month/day/weekday/hour와 시간대 연산을 열어 줍니다. pandas는 날짜를 문자열('2024-01-01')과 직접 비교할 수 있습니다. 시간대 인식 작업은 tz_localize(tz 추가)와 tz_convert(tz 변경)를 쓰며 naive와 aware datetime을 섞지 마세요.

pandas
df["date"] = pd.to_datetime(df["date"])

# Extract parts
df["year"]      = df["date"].dt.year
df["month"]     = df["date"].dt.month
df["day"]       = df["date"].dt.day
df["weekday"]   = df["date"].dt.day_name()    # 'Monday'
df["hour"]      = df["date"].dt.hour
df["is_weekend"] = df["date"].dt.dayofweek >= 5

# Date arithmetic
df["age_days"] = (pd.Timestamp("today") - df["date"]).dt.days

# Format back to string
df["date_str"] = df["date"].dt.strftime("%Y-%m-%d")

# Timezone handling
df["date_utc"] = df["date"].dt.tz_localize("UTC")
df["date_local"] = df["date_utc"].dt.tz_convert("US/Eastern")

# Filter by date
df[df["date"] > "2024-01-01"]
df[df["date"].between("2024-01-01", "2024-12-31")]
07

GroupBy와 집계

기본 GroupBy

groupby는 split-apply-combine을 따릅니다. 그룹 키로 행을 나누고, 그룹마다 함수를 적용하고, 결과를 결합합니다. groupby('city')['age'].mean()은 city를 인덱스로 하는 Series를 반환하고, list를 준 agg는 DataFrame을 반환합니다. size()는 (NaN 키 포함) 그룹별 모든 행을 세고, value_counts()는 NaN을 제외하고 빈도순 정렬합니다. 여러 그룹 키가 계층 인덱스를 만듭니다.

pandas
# Split-Apply-Combine: group rows, compute per group
df.groupby("city")["age"].mean()         # one column, one agg
df.groupby("city")["age"].agg(["mean", "median", "std"])

# Multiple columns
df.groupby("city")[["age", "score"]].mean()

# Group by multiple columns (hierarchical)
df.groupby(["city", "pass"])["age"].mean()

# Quick counts per group
df.groupby("city").size()                # includes NaN groups
df["city"].value_counts()                # excludes NaN, sorted

# Iterate over groups
for name, group in df.groupby("city"):
    print(name, len(group))

다중 집계

명명 집계(pandas 0.25+)가 가장 깔끔한 방법입니다. 출력 컬럼이 MultiIndex 대신 지정한 이름을 받습니다. 문법은 new_col=('source_col', 'function')입니다. lambda를 통한 커스텀 함수는 동작하지만 내장(mean, sum 등은 C 최적화)보다 느립니다. 그룹 키를 일반 컬럼으로 원하면 항상 reset_index()하세요.

pandas
# Different aggregations per column
df.groupby("city").agg({
    "age":   ["mean", "median", "std"],
    "score": ["min", "max", "count"],
})

# Named aggregations (cleaner output, no MultiIndex)
result = df.groupby("city").agg(
    avg_age=("age", "mean"),
    median_age=("age", "median"),
    n_people=("age", "count"),
    max_score=("score", "max"),
)

# Custom aggregation function
df.groupby("city").agg(
    age_range=("age", lambda x: x.max() - x.min()),
)

# Reset index to get a flat DataFrame
result = result.reset_index()

transform과 filter

transform은 마법 같습니다. 입력과 같은 길이의 Series를 반환하며 각 그룹의 결과를 그 멤버에게 broadcasting합니다. 원본 행 옆에 그룹 수준 통계(카테고리별 평균)를 더하거나, 그룹 평균으로 결측을 채우는 데 완벽합니다. filter는 그룹별 불리언 조건으로 전체 그룹을 유지하거나 버립니다(예: 샘플이 너무 적은 도시 드롭).

pandas
# transform: broadcast group result back to original shape
df["age_mean_city"] = df.groupby("city")["age"].transform("mean")
df["age_dev"] = df["age"] - df.groupby("city")["age"].transform("mean")

# Fill missing with group mean
df["score"] = df.groupby("city")["score"].transform(
    lambda s: s.fillna(s.mean()))

# filter: keep/drop entire groups based on a condition
# keep groups with more than 2 rows
big_groups = df.groupby("city").filter(lambda g: len(g) > 2)
# keep groups where average score > 80
df.groupby("city").filter(lambda g: g["score"].mean() > 80)

그룹에 apply

groupby의 apply가 가장 유연하지만(그룹마다 임의 함수) 가장 느립니다. 가능하면 내장 집계(mean, sum)나 transform을 선호하세요. 함수가 Series를 반환하면 Series 인덱스가 컬럼인 DataFrame이 만들어집니다. idxmax가 최대의 인덱스를 반환하며 같은 행의 다른 컬럼을 찾는 데 씁니다.

pandas
# Apply any function per group (most flexible)
def top_scorer(g):
    return g.nlargest(1, "score")

df.groupby("city").apply(top_scorer)
df.groupby("city").apply(lambda g: g.nlargest(2, "score"))

# Normalize within group
df.groupby("city").apply(
    lambda g: (g["score"] - g["score"].mean()) / g["score"].std()
)

# Multiple results per group
def summarize(g):
    return pd.Series({
        "count": len(g),
        "avg_score": g["score"].mean(),
        "top_name": g.loc[g["score"].idxmax(), "name"],
    })

df.groupby("city").apply(summarize)

# include_groups=False (newer pandas) to exclude group cols from g

피벗 테이블과 Crosstab

pivot_table은 groupby + unstack의 결합입니다. 긴 데이터를 (예: 도시 × 합격별 평균 점수) 행렬로 만드는 데 완벽합니다. margins=True가 행/열 합계를 더합니다. crosstab은 조합 세기(빈도표)의 특화 피벗이며 normalize='index'가 행 비율을 줍니다. Melt는 그 역으로 넓은 형식을 다시 긴 형식으로 만듭니다.

pandas
# pivot_table: groupby + reshape in one step
pd.pivot_table(df, values="score", index="city", columns="pass",
               aggfunc="mean")
pd.pivot_table(df, values="score", index="city", columns="pass",
               aggfunc=["mean", "count"], margins=True)

# Multiple values
pd.pivot_table(df, values=["age", "score"], index="city",
               aggfunc={"age": "mean", "score": "max"})

# crosstab: frequency table of two (or more) categoricals
pd.crosstab(df["city"], df["pass"])
pd.crosstab(df["city"], df["pass"], normalize="index")  # row %
pd.crosstab(df["city"], df["pass"], values=df["score"],
            aggfunc="mean")  # like a pivot

# Melt a pivot back to long
wide = pd.pivot_table(df, values="score", index="city", columns="pass")
long = wide.reset_index().melt(id_vars="city", var_name="pass",
                                value_name="score")
08

병합과 조인

merge (SQL식 조인)

merge가 pandas의 SQL JOIN이며 how가 inner/left/right/outer/cross를 제어합니다. 항상 on을 명시하세요. 키 이름이 다르면 left_on/right_on을 쓰고, 겹치는 컬럼 구분에는 suffixes를 쓰세요(기본 _x/_y는 불투명). validate='m:1'(또는 '1:1','1:m','m:m')은 조인 카디널리티가 틀리면 오류를 내며 실수로 인한 행 중복의 훌륭한 안전장치입니다.

pandas
# Like SQL JOIN
pd.merge(df1, df2, on="id")                     # inner join (default)
pd.merge(df1, df2, on="id", how="left")         # left join
pd.merge(df1, df2, on="id", how="right")
pd.merge(df1, df2, on="id", how="outer")        # full outer
pd.merge(df1, df2, on="id", how="cross")        # cartesian product

# Different column names in each frame
pd.merge(df1, df2, left_on="user_id", right_on="id")

# Join on index
pd.merge(df1, df2, left_index=True, right_index=True)

# Suffixes for overlapping non-key columns
pd.merge(df1, df2, on="id", suffixes=("_left", "_right"))

# Validate to catch unexpected duplicates
pd.merge(df1, df2, on="id", validate="m:1")  # many-to-one expected

concat (스태킹)

concat은 DataFrame을 수직(axis=0, 기본) 또는 수평(axis=1)으로 쌓습니다. ignore_index=True는 원본 인덱스를 버리고 깨끗한 0..n-1을 만듭니다. 스태킹에서는 보통 이것이 원하는 것입니다. join='inner'는 공유 컬럼만 유지하며(프레임이 벗어났을 때 유용) verify_integrity=True는 중복 인덱스에서 오류를 냅니다. 지저분한 append의 안전망입니다.

pandas
# Stack vertically (rows) — same columns
pd.concat([df1, df2])
pd.concat([df1, df2], ignore_index=True)   # reindex 0..n-1

# Stack horizontally (columns)
pd.concat([df1, df2], axis=1)

# Concat with keys (hierarchical index)
pd.concat([df1, df2], keys=["q1", "q2"])

# Append (deprecated; use concat)
# df1.append(df2)  # deprecated, use pd.concat

# Verify columns match when stacking
pd.concat([df1, df2], verify_integrity=True)  # error on dup index

# Join options for mismatched columns
pd.concat([df1, df2], join="inner")  # keep only shared columns
pd.concat([df1, df2], join="outer")  # keep all, NaN for missing

join (인덱스 기반)

join은 (인덱스로 조인하는 흔한 경우의) merge에 대한 문법 설탕이며 양쪽 프레임이 이미 의미 있는 인덱스를 가질 때 약간 더 간결합니다. 컬럼으로 조인할 때는 merge가 더 명확합니다. join은 (리스트를 전달해) 여러 DataFrame을 한 번에 조인할 수 있어 여러 룩업 테이블을 메인 프레임에 합칠 때 편리합니다.

pandas
# join is merge optimized for joining on the index
df1.join(df2)                          # join on index
df1.join(df2, how="left")              # left, right, inner, outer
df1.join([df2, df3])                   # join multiple at once

# join on a column (set index first)
df1.set_index("id").join(df2.set_index("id"), how="inner")

# Suffix for overlapping columns
df1.join(df2, lsuffix="_left", rsuffix="_right")

# When to use join vs merge:
# - join: keys are the index (faster, cleaner)
# - merge: keys are regular columns (more flexible)

combine과 update

combine_first가 (SQL의 coalesce처럼) 다른 DataFrame으로 결측을 채우는 관용적 방법입니다. update는 df1을 제자리 수정하며 df2에 non-NaN 값이 있는 곳만 덮어씁니다. 더 새로운 부분 데이터로 마스터 데이터셋을 패치하는 데 훌륭합니다. concat + drop_duplicates가 빠른 합집합/중복 제거이지만 진짜 집합 연산에는 indicator=True를 준 merge를 고려하세요.

pandas
# combine_first: fill NaN in df1 with values from df2
df1.combine_first(df2)
# Where df1 is NaN, take df2's value; otherwise keep df1.

# update: overwrite df1 in place with non-NaN from df2
df1.update(df2)

# combine with a custom function
import numpy as np
df1.combine(df2, lambda s1, s2: np.minimum(s1, s2))

# Concat then drop duplicates (union with dedup)
pd.concat([df1, df2]).drop_duplicates()

병합 결과 확인

indicator=True가 조인 디버깅에 귀중합니다. 어느 행이 어느 쪽에서 왔는지 알려 줍니다. 병합 후 행 수의 갑작스러운 점프는 보통 한 프레임의 중복 키를 뜻하므로, 조인 전 키에 value_counts()로 확인하세요. '키가 df2에 존재하는 df1의 행으로 필터'에는 (세미 조인인) isin을 쓰세요. 실제 병합이 필요 없습니다.

pandas
# indicator=True adds a '_merge' column showing the source
merged = pd.merge(df1, df2, on="id", how="outer", indicator=True)
# _merge values: 'left_only', 'right_only', 'both'

# Find rows in df1 but not df2 (anti-join)
only_left = merged[merged["_merge"] == "left_only"]

# Find rows in both (intersection)
both = merged[merged["_merge"] == "both"]

# Detect unexpected row explosion (duplicate keys)
print(len(df1), len(df2), len(merged))
# if len(merged) >> max(len(df1), len(df2)) you have duplicate keys

# isin for a simple semi-join (filter df1 to keys in df2)
df1[df1["id"].isin(df2["id"])]            # semi-join
df1[~df1["id"].isin(df2["id"])]           # anti-join
09

데이터 리셰이핑

melt (wide→long)

melt는 넓은 형식(엔티티당 한 행, 측정 컬럼 다수)을 긴 형식(측정당 한 행)으로 바꿉니다. 대부분의 ML/통계 라이브러리가 선호하는 tidy 형식입니다. id_vars는 그대로 유지되는 식별 컬럼이고 나머지는 var/value 쌍이 됩니다. 긴 형식이 groupby, 필터, 플롯이 더 쉽습니다.

pandas
# melt: unpivot columns into rows
df_wide = pd.DataFrame({
    "id": [1, 2],
    "q1": [10, 20],
    "q2": [15, 25],
    "q3": [20, 30],
})

long = df_wide.melt(id_vars="id", var_name="quarter", value_name="score")
#    id quarter  score
# 0   1      q1     10
# 1   2      q1     20
# ...

# Melt only specific columns
df_wide.melt(id_vars="id", value_vars=["q1", "q2"])

# Keep the wide columns too (with identifier)
df_wide.melt(id_vars="id", value_vars=["q1","q2","q3"],
             var_name="quarter", value_name="score",
             ignore_index=True)

pivot (long→wide)

pivot은 집계 없이 long을 wide로 리셰이프하며 (index, columns) 쌍이 중복이면 실패합니다. 그 경우 aggfunc를 준 pivot_table을 쓰세요. 컬럼 이름이 피벗의 컬럼이 되어 혼란스러울 수 있으니 reset_index()와 columns.name=None으로 결과를 정리하세요. pivot은 melt의 역입니다.

pandas
# pivot: long to wide (without aggregation)
df_long = pd.DataFrame({
    "id": [1, 1, 1, 2, 2, 2],
    "quarter": ["q1", "q2", "q3", "q1", "q2", "q3"],
    "score": [10, 15, 20, 30, 35, 40],
})

wide = df_long.pivot(index="id", columns="quarter", values="score")
# quarter  q1  q2  q3
# id
# 1        10  15  20
# 2        30  35  40

# pivot fails on duplicate index/value combos — use pivot_table then
df_long.pivot_table(index="id", columns="quarter",
                    values="score", aggfunc="sum")

# Restore a regular column from the index
wide = wide.reset_index()
wide.columns.name = None

stack과 unstack

stack/unstack은 MultiIndex 객체에서 행과 컬럼 사이의 수준을 옮기며 그룹 결과 리셰이핑에 강력합니다. 여러 키의 groupby가 MultiIndex의 Series를 만들고, unstack이 한 수준을 컬럼으로 바꿔 행렬 뷰를 만듭니다. stack은 그 역입니다. 이들이 내부에서 피벗 테이블의 구성 요소입니다.

pandas
# MultiIndex column example
df = pd.DataFrame({
    ("A", "x"): [1, 2],
    ("A", "y"): [3, 4],
    ("B", "x"): [5, 6],
})

# stack: turn column level into inner row index
stacked = df.stack()
# Now a Series with MultiIndex (row, col_level_2)

# unstack: inverse — turn row level into column level
stacked.unstack()

# Common use: reshape grouped result
g = df.groupby(["city", "year"])["score"].mean()
# city  year
# NYC   2023    80
# NYC   2024    85
# LA    2023    70

g.unstack("year")  # years become columns
#        2023  2024
# city
# NYC    80    85
# LA     70    NaN

리스트 폭발

explode는 리스트의 컬럼을 리스트 요소당 한 행으로 만들며 다른 컬럼을 복제합니다. 중첩 데이터(JSON 배열, 다중 태그 레코드)에 필수입니다. 분석 전 리스트 값 컬럼을 정규화하는 깔끔한 방법입니다. 반대 방향(행을 리스트로 합치기)에는 groupby + apply(list)를 쓰세요.

pandas
# explode: turn list-like values into separate rows
df = pd.DataFrame({
    "id": [1, 2],
    "tags": [["python", "ml"], ["sql", "db", "etl"]],
})
#              id           tags
# 0             1  [python, ml]
# 1             2  [sql, db, etl]

exploded = df.explode("tags")
#    id    tags
# 0   1  python
# 0   1      ml
# 1   2     sql
# 1   2      db
# 1   2    etl

# Useful after str.split
df["tags"] = df["tags_str"].str.split(",")
exploded = df.explode("tags")

# Aggregate back: groupby + list
exploded.groupby("id")["tags"].apply(list)

MultiIndex 연산

MultiIndex(계층 인덱스)는 고차원 데이터를 2D로 표현하게 합니다. xs(교차 단면)가 외부 수준을 모두 지정하지 않고 특정 수준에서 선택합니다. swaplevel과 sort_index(level=)가 다른 뷰를 위해 수준을 재정렬합니다. 대부분의 경우 reset_index()가 MultiIndex를 다루기 쉬운 일반 컬럼으로 평탄화합니다.

pandas
# Create a MultiIndex DataFrame
idx = pd.MultiIndex.from_tuples([("NYC", 2023), ("NYC", 2024),
                                  ("LA", 2023)], names=["city", "year"])
df = pd.DataFrame({"score": [80, 85, 70]}, index=idx)

# Select by outer level
df.loc["NYC"]              # all NYC rows
df.xs("NYC", level="city") # same, more explicit

# Select by inner level
df.xs(2023, level="year")

# Swap levels
df.swaplevel()

# Sort by level
df.sort_index(level="year")

# Reset one level back to a column
df.reset_index(level="year")

# Flatten columns after a groupby
g = df.groupby(["city", "year"]).mean().reset_index()
10

정렬과 순위

값 정렬

컬럼 목록과 맞는 ascending 목록을 준 sort_values가 사전식으로 정렬합니다. 1차 키 먼저, 그다음 동률 깨기. na_position이 NaN 위치를 제어합니다(기본 'last'). 정렬은 안정적이므로 같은 키는 원본 순서를 유지합니다. 정렬이 인덱스 순서를 바꾸며 그 뒤 reset_index(drop=True)가 깨끗한 순차 인덱스를 줍니다.

pandas
# Sort by one column
df.sort_values("age")
df.sort_values("age", ascending=False)

# Sort by multiple columns (stable sort)
df.sort_values(["city", "age"], ascending=[True, False])
# city ascending, age descending within each city

# Put NaNs first or last
df.sort_values("score", na_position="first")

# In-place (modifies df)
df.sort_values("age", inplace=True)

# Sort by index
df.sort_index()
df.sort_index(axis=1)            # sort columns by name
df.sort_index(ascending=False)

# Reset index after sorting
df.sort_values("age").reset_index(drop=True)

순위 매기기

rank는 백분위, 그룹 내 top-N, 비모수 통계 계산에 필수입니다. method='dense'는 (갭 없는) 1,2,2,3을 주며 메달이나 성적에 좋고, 'first'는 출현 순서로 동률을 깹니다. rank(pct=True)가 백분위를 반환합니다. groupby + rank가 그룹 내 순위(예: 지역별 최고 판매자)를 계산합니다.

pandas
# Default rank: average for ties (1, 2.5, 2.5, 4)
df["rank"] = df["score"].rank()

# Methods for handling ties
df["score"].rank(method="average")  # default
df["score"].rank(method="min")      # ties get the min rank
df["score"].rank(method="max")      # ties get the max rank
df["score"].rank(method="first")    # ties broken by order of appearance
df["score"].rank(method="dense")    # 1, 2, 2, 3 (no gaps)

# Ascending / descending
df["score"].rank(ascending=False)   # highest = rank 1

# Rank as percentile
df["pct"] = df["score"].rank(pct=True)

# Rank within groups
df["city_rank"] = df.groupby("city")["score"].rank(ascending=False)

nlargest와 nsmallest

nlargest/nsmallest는 최적화되어 내부에서 힙을 쓰므로, 몇 개 행만 필요할 때(예: 백만 개 중 top 10) 전체 프레임 정렬보다 빠릅니다. '그룹별 top N'에는 groupby + apply(nlargest)가 관용구지만 일부 데이터에서는 전체 정렬 + groupby head보다 느립니다. keep이 동률 처리를 제어합니다('first', 'last', 'all').

pandas
# Top N rows — faster than sort_values + head on large data
df.nlargest(5, "score")            # top 5 by score
df.nlargest(5, "score", keep="first")  # tie-breaking
df.nsmallest(3, "age")             # youngest 3

# Top N per group
df.groupby("city").apply(lambda g: g.nlargest(2, "score"))

# Bottom N with multiple columns
df.nsmallest(5, ["age", "score"])

# Equivalent sort_values (slower for big data)
df.sort_values("score", ascending=False).head(5)

인덱스와 컬럼 정렬

sort_index(axis=1)가 컬럼을 알파벳순 정렬합니다. 병합이 임의 순서로 새 컬럼을 더한 뒤 편리합니다. (‘id’, ‘name’ 같은) 키 컬럼을 앞으로 두려면 리스트 연결을 쓰세요. 앞 컬럼 다음 나머지. 명시적 컬럼 선택 df[[...]]가 재정렬의 가장 명확한 방법이며 컬럼 서브셋 방법이기도 합니다.

pandas
# Sort the row index
df.sort_index()
df.sort_index(ascending=False)

# Sort columns alphabetically
df.sort_index(axis=1)
df.sort_index(axis=1, ascending=False)

# Reorder columns explicitly
df[["name", "age", "city", "score"]]

# Reorder to a pattern
cols = sorted(df.columns)
df = df[cols]

# Move specific columns to the front
front = ["id", "name"]
df = df[front + [c for c in df.columns if c not in front]]

키를 곁들인 정렬

sort_values(key=)는 정렬 전 컬럼에 함수를 적용합니다. 대소문자 무시 또는 길이 기반 정렬입니다. 순서형 범주 컬럼은 알파벳순이 아니라 정의된 카테고리 순서로 정렬됩니다. 요일, 크기(S<M<L), 커스텀 비즈니스 순서에 좋습니다. 자연 정렬(file1, file2, file10)에는 숫자를 분리하는 커스텀 키가 필요합니다.

pandas
# Sort by a function of the values (key, like sorted())
df.sort_values("name", key=lambda s: s.str.lower())
# case-insensitive sort

# Sort by string length
df.sort_values("name", key=lambda s: s.str.len())

# Sort by a custom order (categorical)
df["city"] = pd.Categorical(df["city"],
    categories=["NYC", "LA", "SF"], ordered=True)
df.sort_values("city")  # follows the defined category order

# Natural sort (numbers in strings)
import re
def natural_key(s):
    return [int(t) if t.isdigit() else t for t in re.split(r"(\d+)", s)]
df.sort_values("version", key=lambda s: s.map(natural_key))
11

Datetime 연산

날짜 파싱

형식을 알면 항상 명시적 형식 문자열을 전달하세요. 추론보다 10배 빠르고 모호함을 피합니다(01/02/2024는 1월 2일 또는 2월 1일일 수 있음). errors='coerce'는 파싱 불가 값을 (datetime의 NaN인) NaT(Not a Time)로 바꿉니다. year/month/day 컬럼이 있는 DataFrame에 pd.to_datetime을 쓰면 부분들로 날짜를 구성합니다.

pandas
# Parse strings to datetime
df["date"] = pd.to_datetime(df["date"])
df["date"] = pd.to_datetime(df["date"], format="%Y-%m-%d")  # faster + safer

# Handle mixed formats
df["date"] = pd.to_datetime(df["date"], format="mixed")

# Coerce bad values to NaT (datetime NaN)
df["date"] = pd.to_datetime(df["date"], errors="coerce")

# Parse on read
df = pd.read_csv("data.csv", parse_dates=["date", "created_at"])

# Parse multiple columns into one
df["datetime"] = pd.to_datetime(df[["year", "month", "day"]])

# Timestamp (scalar)
pd.Timestamp("2024-06-15 14:30:00")
pd.Timestamp.now()
pd.Timestamp("2024-06-15").tz_localize("UTC")

date_range와 Periods

date_range는 유연한 freq 문자열로 DatetimeIndex 시퀀스를 생성합니다. 'D'(일), 'H'(시), 'MS'(월 시작), 'W-MON'(매주 월요일), 'Q'(분기). bdate_range가 주말을 건너뜁니다. Period는 순간이 아니라 구간(한 달 전체, 한 분기 전체)을 나타내며 보고 기간에 유용합니다. freq 별칭이 강력합니다: '2D' = 2일마다.

pandas
# Generate a sequence of dates
pd.date_range("2024-01-01", "2024-01-10")           # daily
pd.date_range("2024-01-01", periods=10)             # 10 days
pd.date_range("2024-01-01", periods=10, freq="H")   # hourly
pd.date_range("2024-01-01", "2024-12-31", freq="MS") # month start
pd.date_range("2024-01-01", "2024-12-31", freq="W-MON") # weekly Mondays

# Business days only
pd.bdate_range("2024-01-01", periods=10)

# Period (represents an interval, like a month)
p = pd.Period("2024-06", freq="M")
p.to_timestamp()    # convert to the month's start
p.start_time, p.end_time

# Period range
pd.period_range("2024-01", "2024-12", freq="M")

리샘플링과 주파수 변환

resample은 시계열의 groupby입니다. 집계로 다운샘플(W/M/Q 합과 평균)하고, 채움(ffill, interpolate)으로 업샘플하세요. resample에는 DatetimeIndex가 필요합니다. 'label'과 'closed' 인자가 bin 경계가 왼쪽 또는 오른쪽 기간에 속하는지 제어하며, 주간/월간 집계의 1픽셀 어긋남 오류를 피하는 데 중요합니다.

pandas
ts = pd.Series(range(100), index=pd.date_range("2024-01-01", periods=100, freq="D"))

# Downsample (more frequent -> less frequent): use agg
ts.resample("W").sum()       # weekly sum
ts.resample("M").mean()      # monthly mean
ts.resample("QE").max()      # quarterly max

# Upsample (less -> more frequent): need fill
ts.resample("H").asfreq()            # hourly, NaN for gaps
ts.resample("H").ffill()             # forward fill
ts.resample("H").interpolate()       # linear interp

# Custom aggregation
ts.resample("W").agg(["mean", "std", "count"])

# Resample with multiple columns
df.resample("M").agg({"sales": "sum", "visits": "mean"})

# Use 'label' and 'closed' to control bin edges
ts.resample("M", label="right", closed="right").sum()

Shifting과 Lag

shift, diff, pct_change가 시계열 피처 엔지니어링의 기초입니다. shift(1)가 (어제 값을 오늘 행에 정렬한) 래그를 만들어 자기회귀 피처에 완벽합니다. shift(-1)은 미래를 엿보며(다음 단계 타깃 구축용) diff와 pct_change가 변화를 측정합니다. 이들을 쓰기 전에 항상 시간순 정렬하고 경계의 NaN에 주의하세요.

pandas
# Shift values forward/backward (for time-series features)
ts.shift(1)          # move values down by 1 (yesterday's value)
ts.shift(-1)         # move up by 1 (tomorrow's value)

# Difference (today - yesterday)
ts.diff()            # first difference
ts.diff(7)           # week-over-week difference

# Percentage change
ts.pct_change()
ts.pct_change(periods=7)  # 7-day pct change

# Lag features for ML
df["lag_1"]  = df["sales"].shift(1)
df["lag_7"]  = df["sales"].shift(7)
df["roll_7"] = df["sales"].rolling(7).mean()
df["target_next"] = df["sales"].shift(-1)  # next-day target

# Shift by a time frequency
ts.shift(1, freq="D")   # shift the INDEX by 1 day

Rolling과 Expanding 윈도우

rolling이 슬라이딩 윈도우 위의 통계를 계산합니다. 이동 평균, 변동성 등. min_periods가 부분 윈도우 계산을 허용합니다(아니면 처음 N-1이 NaN). ewm은 지수 가중 이동 평균을 주며(최근 점에 더 가중. 금융에서 흔함) expanding은 시작부터 커집니다(누적 통계). ('7D' 같은) 시간 기반 윈도우는 행 수 윈도우와 달리 불규칙 표본을 올바르게 처리합니다.

pandas
s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=float)

# Rolling window (fixed-size sliding window)
s.rolling(3).mean()        # 3-period moving average
s.rolling(7).std()
s.rolling(3, min_periods=1).mean()  # allow partial windows

# Custom aggregation
s.rolling(3).apply(lambda x: x.max() - x.min())

# Exponentially weighted (decaying weights)
s.ewm(span=7).mean()       # EWMA — recent data weighted more
s.ewm(alpha=0.3).mean()

# Expanding window (grows from start)
s.expanding().mean()       # cumulative mean
s.expanding().max()        # running max

# Window with time-based offset (needs DatetimeIndex)
ts.rolling("7D").mean()    # 7-day window, not 7 rows
12

범주형 데이터

범주형 생성

category dtype은 문자열을 정수 코드 + 룩업 테이블로 저장합니다. 저카디널리티 컬럼(5개 고유 값의 city 컬럼과 백만 행)에서 큰 메모리 절약입니다. 순서형 범주는 비교(size > 'M')를 지원하며 알파벳순이 아니라 카테고리 순서로 정렬합니다. 알려진 작은 값 집합의 컬럼에는 category를 쓰세요.

pandas
# Convert to category dtype
df["city"] = df["city"].astype("category")

# Create with explicit categories
s = pd.Categorical(["a", "b", "a", "c"],
                    categories=["a", "b", "c", "d"])

# Ordered categorical (for sorting & comparisons)
size = pd.Categorical(["M", "L", "S", "XL"],
                       categories=["S", "M", "L", "XL"],
                       ordered=True)
size > "M"  # works because it's ordered

# Memory savings
df["city"].memory_usage(deep=True)              # object
df["city"].astype("category").memory_usage(deep=True)  # much less

.cat 접근자

.cat 접근자가 범주 메타데이터를 조작합니다. remove_unused_categories가 카테고리 목록을 실제 값으로 다듬습니다. 필터링 후 많은 카테고리가 비게 되므로 중요합니다. rename_categories가 기저 코드를 바꾸지 않고 레이블을 바꾸고, reorder_categories가 정렬 순서를 바꿉니다. 이들은 모두 새 Series를 반환하므로 적용하려 재할당하세요.

pandas
s = pd.Series(["a", "b", "a", "c"], dtype="category")

# Inspect categories
s.cat.categories        # Index(['a', 'b', 'c'])
s.cat.codes             # integer codes
s.value_counts()

# Add / remove categories
s = s.cat.add_categories(["d"])
s = s.cat.remove_categories(["d"])     # values in 'd' become NaN
s = s.cat.remove_unused_categories()

# Rename categories
s = s.cat.rename_categories({"a": "alpha", "b": "beta"})

# Reorder categories
s = s.cat.reorder_categories(["c", "b", "a"])

# Set / unset ordering
s = s.cat.as_ordered()
s = s.cat.as_unordered()

범주형 연산

범주형 연산은 groupby와 value_counts에서 object(문자열) 연산보다 일반적으로 빠릅니다. 두 범주형 컬럼을 병합할 때는 먼저 set_categories로 카테고리 집합을 정렬하세요. 어긋난 카테고리는 느린 병합과 조용한 NaN을 낳습니다. 범주 오버헤드가 가치 없을 때(예: 자유 텍스트 컬럼) astype(str)으로 문자열/object로 되돌리세요.

pandas
# Operations preserve categorical dtype where possible
s = pd.Series(["low", "high", "med", "low"], dtype="category")
s.value_counts()

# Comparison on ordered categoricals
size = pd.Series(["M", "L", "S"], dtype="category")
size = size.cat.as_ordered().cat.reorder_categories(["S","M","L","XL"])
size > "M"   # boolean Series

# Groupby works as expected
df.groupby("city")["score"].mean()

# Converting back
df["city"] = df["city"].astype(str)         # to string
df["city"] = df["city"].astype("object")    # to object

# Beware: merges between categoricals can be slow if categories differ
# Align categories before merging:
cats = sorted(set(df1["city"].cat.categories) |
              set(df2["city"].cat.categories))
df1["city"] = df1["city"].cat.set_categories(cats)
df2["city"] = df2["city"].cat.set_categories(cats)

메모리 최적화

큰 데이터 로드 시 메모리 최적화가 중요합니다. 저카디널리티 문자열을 category로(10~100배 절약), 수치를 다운캐스트(작은 범위 정수는 int64->int8, float64->float32)하세요. 'string' dtype(pandas 1.0+)이 object보다 메모리 효율적이고 NaN을 더 잘 다룹니다. 경험칙: nunique/len < 0.5면 category가 가치 있습니다.

pandas
# Check current memory
df.info(memory_usage="deep")

# Convert object columns to category when cardinality is low
for col in df.select_dtypes(include="object"):
    if df[col].nunique() / len(df) < 0.5:  # <50% unique
        df[col] = df[col].astype("category")

# Downcast numeric columns
df["age"] = pd.to_numeric(df["age"], downcast="integer")
df["score"] = pd.to_numeric(df["score"], downcast="float")

# Use string dtype (pandas 1.0+) instead of object
df["name"] = df["name"].astype("string")

# Compare memory before/after
before = df.memory_usage(deep=True).sum()
# ... optimize ...
after = df.memory_usage(deep=True).sum()
print(f"Reduced from {before/1e6:.1f}MB to {after/1e6:.1f}MB")

더미 변수 (One-Hot)

get_dummies가 범주형 컬럼을 0/1 지표 컬럼으로 원-핫 인코딩합니다. 범주형을 다루지 못하는 선형 모델 전에 필수입니다. drop_first가 선형 회귀의 더미 변수 함정(다중공선성)을 피합니다. ML 파이프라인에서는 get_dummies보다 sklearn의 OneHotEncoder를 선호하세요(테스트 시 보지 못한 카테고리를 handle_unknown='ignore'로 처리).

pandas
# One-hot encode categoricals
pd.get_dummies(df["city"])
pd.get_dummies(df, columns=["city", "pass"])  # encode multiple

# Drop first to avoid multicollinearity (for linear models)
pd.get_dummies(df["city"], drop_first=True)

# With a prefix
pd.get_dummies(df["city"], prefix="city")

# From categorical with all categories
pd.get_dummies(df["city"].astype("category"))

# Alternatively, sklearn's OneHotEncoder (for ML pipelines)
from sklearn.preprocessing import OneHotEncoder
ohe = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
X_ohe = ohe.fit_transform(df[["city"]])
13

성능과 최적화

벡터화 (iterrows 회피)

iterrows가 pandas 성능의 1위 죄입니다. 벡터화 연산보다 100~1000배 느립니다. 항상 벡터화된 컬럼 연산(df['a'] + df['b']), 문자열에는 .str, if-else에는 np.where을 선호하세요. 정말 루프해야 한다면 iterrows보다 itertuples가 훨씬 빠릅니다(namedtuples vs Series). 복잡한 로직은 numba나 cython을 고려하거나 .to_numpy()로 numpy로 추출하세요.

pandas
# BAD: iterrows is extremely slow
for idx, row in df.iterrows():
    df.loc[idx, "x"] = row["a"] + row["b"]

# GOOD: vectorized operations
df["x"] = df["a"] + df["b"]

# GOOD: .str accessor for strings
df["name"] = df["name"].str.upper()

# GOOD: np.where for conditionals
df["cat"] = np.where(df["a"] > 0, "pos", "neg")

# If you must iterate (rare), use itertuples (faster than iterrows)
for row in df.itertuples():
    process(row.a, row.b)

# Or .to_numpy() / .values for raw array loops
for row in df[["a", "b"]].to_numpy():
    ...

# Benchmark
%timeit df["a"] + df["b"]
%timeit df.apply(lambda r: r["a"] + r["b"], axis=1)

eval과 query

eval과 query는 문자열 표현식을 파싱해 numexpr로 평가하며, 큰 DataFrame에서 중간 배열 생성을 피하고 C 수준 평가를 쓰므로 Python 산술보다 2~4배 빠를 수 있습니다. 작은 데이터에서는 (파싱 오버헤드로) 이득이 줄어듭니다. 큰 프레임의 복잡한 표현식에 유용하지만 항상 벤치마크하세요. 항상 빠른 것은 아닙니다.

pandas
# eval: evaluate string expressions (uses numexpr, faster on big data)
df.eval("total = a + b + c", inplace=True)
df.eval("ratio = a / (b + c)")
df.eval("c = a > b")

# Multiple operations in one eval (efficient)
df.eval("""
total = a + b
ratio = a / b
flag = a > 10
""", inplace=True)

# query: boolean filter via string (same engine)
df.query("a > 0 and b < 10")

# Local variables with @
threshold = 5
df.query("a > @threshold")

# eval is faster than Python arithmetic on large frames
# because it avoids intermediate arrays

효율적인 dtype

올바른 dtype 선택이 메모리의 가장 쉬운 큰 이득입니다. 정수 다운캐스트(int64->int8은 8배 절약), 저카디널리티 문자열은 category(10~100배), object 대신 'string'. NaN이 있는 정수 컬럼에는 nullable Int64(대문자 I)를 쓰세요. 일반 int64는 NaN을 못 담아 그런 컬럼은 float64로 승격됩니다. 대부분 0인 데이터에는 Sparse dtype이 도움이 됩니다.

pandas
# Downcast numerics
df["age"] = pd.to_numeric(df["age"], downcast="unsigned")  # 0-255
df["score"] = pd.to_numeric(df["score"], downcast="float")

# Use category for low-cardinality strings
df["city"] = df["city"].astype("category")

# Use 'string' dtype instead of object
df["name"] = df["name"].astype("string")

# Use Nullable integers (Int64 with capital I) for ints with NaN
df["count"] = df["count"].astype("Int64")  # supports NaN

# Sparse for mostly-zero data
s = pd.Series([0, 0, 0, 1, 0, 0]).astype("Sparse[int]")

# Compare memory
df["city"].astype("object").memory_usage(deep=True)
df["city"].astype("category").memory_usage(deep=True)

청크 처리

read_csv(chunksize=...)가 이터레이터를 반환하며 각 청크가 그 행 수의 DataFrame이라 메모리보다 큰 파일을 처리할 수 있습니다. 청크별 집계 후 부분 결과를 결합하세요. SQL의 chunksize는 서버 측 커서를 씁니다. Spark 없이 GB 규모 데이터를 다루는 가장 단순한 방법이며, 진짜 빅데이터에는 Dask나 Polars를 고려하세요.

pandas
# Process a large CSV in chunks (low memory)
chunk_iter = pd.read_csv("huge.csv", chunksize=100_000)

results = []
for chunk in chunk_iter:
    # process each chunk (filter, aggregate, etc.)
    result = chunk.groupby("city")["sales"].sum()
    results.append(result)

# Combine chunk results
total = pd.concat(results).groupby(level=0).sum()

# Or use the iterator directly
for i, chunk in enumerate(pd.read_csv("huge.csv", chunksize=50000)):
    chunk.to_parquet(f"part_{i:04d}.parquet")

# For SQL, use server-side cursors
chunks = pd.read_sql("SELECT * FROM big_table", engine,
                     chunksize=100000)

프로파일링과 벤치마킹

최적화 전 항상 벤치마크하세요. %timeit이 접근 방식을 빠르게 비교합니다. ydata-profiling(예전 pandas-profiling)이 전체 HTML 보고서(통계, 상관, 결측)를 만들어 EDA에 귀중합니다. SettingWithCopyWarning에 주의하세요. 할당이 유지되지 않을 수 있음을 알리며 조용한 버그의 흔한 원천입니다. 개발 중 오류로 잡으려 mode.chained_assignment='raise'를 설정하세요.

pandas
# Time an operation
%timeit df["a"] + df["b"]

# Line profiling (install line_profiler)
# %load_ext line_profiler
# %lprun -f my_function my_function(df)

# Memory profiling (install memory_profiler)
# %load_ext memory_profiler
# %memit df.groupby("city").sum()

# pandas profiling report (install ydata-profiling)
# from ydata_profiling import ProfileReport
# ProfileReport(df).to_file("report.html")

# Quick stats
df.info(memory_usage="deep")
df.describe(include="all")

# Find slow ops
import pandas as pd
pd.set_option("mode.chained_assignment", "warn")  # catch copy bugs
14

데이터베이스와 SQL

SQL에서 읽기

SQLAlchemy 엔진이 커넥션 풀링과 방언 차이를 처리하므로 원시 DBAPI 연결 대신 이를 쓰세요. SQL 주입을 막으려 사용자 제공 값에는 항상 파라미터화된 쿼리(params=)를 쓰세요. chunksize가 큰 테이블을 배치로 스트리밍합니다. 복잡한 쿼리는 SQL로 쓰고(DB가 최적화하도록) 결과는 pandas에 맡기세요.

pandas
from sqlalchemy import create_engine
import pandas as pd

# Create an engine (connection pool)
engine = create_engine("sqlite:///my.db")
engine = create_engine("postgresql://user:pass@host:5432/db")
engine = create_engine("mysql+pymysql://user:pass@host/db")

# Read a whole table
df = pd.read_sql("users", engine)

# Read a query
df = pd.read_sql("SELECT * FROM users WHERE age > 18", engine)

# Parameterized queries (safe from SQL injection)
df = pd.read_sql(
    "SELECT * FROM users WHERE city = %s",
    engine,
    params=("NYC",),
)

# Chunked reads for large tables
for chunk in pd.read_sql("SELECT * FROM big", engine, chunksize=100000):
    process(chunk)

SQL에 쓰기

if_exists='replace'는 테이블을 드롭·재생성하고, 'append'는 행을 더하며, 'fail'(기본)은 테이블이 있으면 오류를 냅니다. method='multi'가 행을 하나의 INSERT 문으로 배칭하며 기본 행별 문장보다 훨씬 빠릅니다. 매우 큰 쓰기에는 chunksize=10000이 메모리와 왕복의 균형입니다. 인덱스가 실제 데이터가 아니면 항상 index=False를 전달하세요.

pandas
# Write a DataFrame to a SQL table
df.to_sql("users", engine, if_exists="replace", index=False)
df.to_sql("users", engine, if_exists="append", index=False)  # add rows

# Specify schema and dtype
from sqlalchemy.types import VARCHAR, INTEGER
df.to_sql("users", engine, if_exists="replace",
          dtype={"name": VARCHAR(100), "age": INTEGER()})

# Write in chunks (for large DataFrames)
df.to_sql("users", engine, if_exists="append",
          chunksize=10000, method="multi")

# method='multi' uses a single INSERT with multiple rows (faster)
# For PostgreSQL, method='multi' with chunksize ~10000 is optimal

# Don't write the index unless it's meaningful data
# index=False avoids a spurious 'index' column

pandas의 SQL식 연산

대부분의 SQL 연산이 pandas에 매핑됩니다. SELECT는 컬럼 선택, WHERE는 불리언 인덱싱, GROUP BY는 groupby, JOIN은 merge, UNION은 concat+drop_duplicates, CASE WHEN은 np.where입니다. 이 매핑을 알면 올바른 도구를 고를 수 있습니다. 서버의 복잡한 조인/집계에는 SQL(DB가 최적화하게), 반복 분석과 플로팅에는 pandas를 쓰세요.

pandas
# SELECT cols
df[["name", "age"]]
# WHERE
df[df["age"] > 18]
# GROUP BY + aggregations
df.groupby("city")["age"].mean()
# ORDER BY
df.sort_values("age", ascending=False)
# LIMIT
df.head(10)
# DISTINCT
df["city"].unique()
df.drop_duplicates(subset=["city"])
# JOIN
pd.merge(df1, df2, on="id", how="inner")
# UNION
pd.concat([df1, df2]).drop_duplicates()
# CASE WHEN
np.where(df["age"] >= 18, "adult", "minor")
# HAVING
g = df.groupby("city").filter(lambda g: g["age"].mean() > 30)

text()로 SQL 실행

SQLAlchemy 2.0은 원시 SQL 문자열에 text()를 요구합니다. 신뢰할 SQL과 그렇지 않은 파라미터를 분리하는 보안 조치입니다. engine.begin()이 성공 시 자동 커밋되고 예외 시 롤백되는 트랜잭션을 열므로 쓰기에는 항상 이것을 쓰세요. 주입을 막으려 :name 바인드 파라미터와 params dict를 쓰세요.

pandas
from sqlalchemy import text

# Use text() for explicit SQL (recommended over raw strings)
query = text("SELECT city, COUNT(*) as n FROM users GROUP BY city")
df = pd.read_sql(query, engine)

# Bind parameters safely
query = text("SELECT * FROM users WHERE age > :min_age AND city = :city")
df = pd.read_sql(query, engine,
                 params={"min_age": 18, "city": "NYC"})

# Execute DDL or DML (non-SELECT)
with engine.begin() as conn:  # transaction
    conn.execute(text("CREATE INDEX idx_city ON users(city)"))
    conn.execute(text("DELETE FROM users WHERE id = :id"),
                 {"id": 999})

Parquet vs CSV vs SQL

Parquet이 저장의 최선 기본입니다. 컬럼형, 압축, dtype 보존(CSV는 dtype을 잃고 매 로드 재추론 강제). Feather는 수명 짧은 캐시에 가장 빠릅니다(Apache Arrow 형식, 직렬화 오버헤드 없음). Pickle은 편리하지만 Python/pandas 버전 간 깨집니다. 데이터가 공유되고 서버 측 질의가 필요하면 SQL을 쓰세요.

pandas
# CSV: human-readable, slow, loses dtypes, large
df.to_csv("data.csv", index=False)
df = pd.read_csv("data.csv")  # re-infers dtypes (slow, error-prone)

# Parquet: binary, fast, preserves dtypes, compressed (best for storage)
df.to_parquet("data.parquet")
df = pd.read_parquet("data.parquet")  # dtypes preserved exactly

# Feather: fastest for short-lived storage (Apache Arrow)
df.to_feather("data.feather")  # requires a RangeIndex
df = pd.read_feather("data.feather")

# Pickle: Python-specific, fast, but version-fragile
df.to_pickle("data.pkl")
df = pd.read_pickle("data.pkl")

# SQL: shared, queryable, but slower for bulk reads
df.to_sql("table", engine)
df = pd.read_sql("SELECT * FROM table", engine)

# Rule of thumb:
# - CSV for human exchange
# - Parquet for storage/archival (best default)
# - Feather for fast cache between Python processes
# - SQL for shared, queryable data
15

시계열 분석

DatetimeIndex 설정

pandas의 시계열 작업은 DatetimeIndex부터 시작합니다. 날짜 컬럼을 인덱스로 설정하고 정렬하세요. 그러면 문자열 슬라이싱(6월 전체는 df.loc['2024-06'])과 resample/rolling/shift를 쓸 수 있습니다. 부분 문자열 인덱싱이 놀랍도록 편리합니다. 설정 후 항상 인덱스를 정렬하세요. 많은 시계열 메서드가 정렬된 인덱스를 요구합니다.

pandas
# Ensure the date column is datetime, then set as index
df["date"] = pd.to_datetime(df["date"])
df = df.set_index("date").sort_index()

# Now you can slice by date strings
df.loc["2024"]                 # all of 2024
df.loc["2024-06"]              # June 2024
df.loc["2024-06-01":"2024-06-15"]  # date range (inclusive)

# Partial string indexing on Series
s = df["value"]
s["2024-06-15"]

# Filter with date strings
df[df.index >= "2024-01-01"]

# A DatetimeIndex unlocks resample, rolling, shift, etc.

실무의 리샘플링

resample이 시계열의 groupby입니다. 'MS'(월 시작), 'ME'(월 끝), 'QE'(분기 끝), 'W'(주간). 카테고리별 리샘플링(예: 도시별 주간 매출)에는 groupby와 결합하세요. asfreq가 (NaN으로 채우며) 빠진 기간의 행을 더해 불규칙 데이터의 갭을 드러내는 데 유용합니다. last() 집계가 각 기간의 마지막 값을 취합니다.

pandas
# Daily -> monthly revenue
daily.resample("MS").sum()

# Common frequencies:
# D=day, B=business day, W=weekly, MS=month start, ME=month end,
# QS=quarter start, YE=year end, H=hour, T/min=minute, S=second

# Multiple aggregations
daily.resample("ME").agg({"sales": "sum", "users": "mean"})

# Resample per group
df.groupby("city").resample("W")["sales"].sum()

# Handle missing periods (fill gaps in the timeline)
daily.asfreq("D")           # add NaN rows for missing days
daily.asfreq("D").ffill()   # fill them

# Quarter-end reporting
daily.resample("QE").last()  # last value of each quarter

시간대

tz_localize는 (값을 바꾸지 않고) naive 타임스탬프에 시간대를 부여하고, tz_convert는 (표시 값을 바꾸며) 다른 시간대로 변환합니다. 둘은 혼동하기 쉽습니다. 항상 먼저 localize하고 나서 convert하세요. DST 전환은 모호하거나 빠진 시간을 만드므로 (정렬된 데이터는) ambiguous='infer' 또는 'NaT'로 처리하세요.

pandas
# Localize naive timestamps (assign a timezone)
s = pd.Series(pd.date_range("2024-01-01", periods=3, freq="H"))
s_localized = s.dt.tz_localize("UTC")
s_localized = s.dt.tz_localize("America/New_York")

# Convert between timezones
s_utc = s.dt.tz_localize("UTC")
s_est = s_utc.dt.tz_convert("US/Eastern")
s_hk  = s_utc.dt.tz_convert("Asia/Hong_Kong")

# On a DatetimeIndex
idx = pd.date_range("2024-01-01", periods=3, freq="H", tz="UTC")
idx = idx.tz_convert("Asia/Shanghai")

# Remove timezone info
s_naive = s_utc.dt.tz_localize(None)

# Ambiguous times (DST fall-back): use 'infer' or 'NaT'
s.dt.tz_localize("US/Eastern", ambiguous="infer")

윈도우 함수

시간 기반 rolling 윈도우('7D')는 불규칙 표본 데이터를 올바르게 처리합니다. 행 수 윈도우(rolling(7))와 달리. ewm(지수 가중)이 최근 관측에 더 가중하며 금융 스무딩의 표준입니다. groupby + rolling이 그룹별 윈도우(예: 주식별 7일 이동 평균)를 계산합니다. groupby+rolling이 만드는 MultiIndex는 reset_index로 정리하세요.

pandas
# Rolling window with time offset
ts.rolling("7D").mean()      # 7-day window (handles irregular sampling)

# Rolling with custom function
ts.rolling("30D").apply(lambda x: np.quantile(x, 0.95))

# Expanding window (cumulative)
ts.expanding(min_periods=10).mean()

# Exponentially weighted
ts.ewm(span=20).mean()       # like a 20-period EWMA
ts.ewm(halflife=10).mean()

# Window per group
df.groupby("city")["sales"].rolling("7D").mean().reset_index(level=0, drop=True)

# Compare rolling vs ewm for smoothing
# ewm weights recent points more — better for fast-changing series

계절성과 분해

seasonal_decompose가 시계열을 추세, 계절, 잔차 성분으로 나눕니다. 구조 이해와 계절성 제거에 유용합니다. period는 주기 길이입니다(연간 계절성이 있는 월간 데이터는 12). index.month나 index.dayofweek로 그룹화하면 계절 패턴이 드러납니다. autocorrelation_plot은 시계열이 자기 래그와 얼마나 상관되는지 보여 줍니다.

pandas
# Seasonal decomposition (needs statsmodels)
from statsmodels.tsa.seasonal import seasonal_decompose

# Additive model: y = trend + seasonal + residual
result = seasonal_decompose(ts, model="additive", period=12)
result.plot()
result.trend, result.seasonal, result.resid

# Multiplicative model: y = trend * seasonal * residual
result = seasonal_decompose(ts, model="multiplicative", period=12)

# Seasonal plots
ts.groupby(ts.index.month).mean()   # average by month
ts.groupby(ts.index.dayofweek).mean()  # by weekday

# Lag plot (autocorrelation check)
pd.plotting.lag_plot(ts, lag=1)
pd.plotting.autocorrelation_plot(ts)
16

시각화

기본 플롯

pandas 플로팅은 matplotlib 위에 만들어졌으며 .plot 접근자가 EDA용 빠른 차트를 줍니다. plot()의 기본은 line(시계열에 좋음), plot.bar()는 범주형 개수, plot.hist()는 분포, plot.scatter()는 관계입니다. 발행 품질 차트에는 seaborn이나 plotly로 전환하지만, 분석 중 빠른 검사에는 pandas 플롯이 타의를 추종하지 않습니다.

pandas
import matplotlib.pyplot as plt

# Line plot (default for time series)
df["score"].plot()
df.plot(x="date", y="score")

# Bar chart
df["city"].value_counts().plot.bar()
df["city"].value_counts().plot.barh()  # horizontal

# Histogram
df["age"].plot.hist(bins=20)
df[["age", "score"]].plot.hist(alpha=0.5, bins=20)

# Scatter
df.plot.scatter(x="age", y="score", c="pass", colormap="viridis")

# Box plot (per group)
df.boxplot(column="score", by="city")

# Area, density, pie
df["city"].value_counts().plot.pie(autopct="%1.1f%%")
df["score"].plot.kde()  # kernel density estimate

plt.tight_layout(); plt.show()

Seaborn 플로팅

Seaborn은 통계 시각화에서 빛납니다. 바이올린 플롯, 페어 플롯(산점도 행렬), 히트맵, 신뢰 구간이 있는 회귀선. matplotlib에서는 장황한 '색으로 그룹'을 우아하게 처리합니다. pairplot이 데이터셋의 모든 쌍별 관계를 훑는 가장 빠른 방법입니다. 항상 DataFrame을 전달하고 컬럼 이름을 쓰세요. seaborn API는 tidy 데이터용으로 설계됐습니다.

pandas
import seaborn as sns
import matplotlib.pyplot as plt

# Statistical plots that pandas can't easily do
sns.histplot(df["score", kde=True])
sns.boxplot(data=df, x="city", y="score")
sns.violinplot(data=df, x="city", y="score")

# Relationships
sns.scatterplot(data=df, x="age", y="score", hue="city")
sns.pairplot(df[["age", "score", "pass"]], hue="pass")

# Correlation heatmap
sns.heatmap(df.corr(numeric_only=True), annot=True, cmap="coolwarm")

# Regression plot
sns.regplot(data=df, x="age", y="score")

# Facet grid (small multiples)
g = sns.FacetGrid(df, col="city", hue="pass")
g.map(sns.histplot, "score")

plt.tight_layout(); plt.show()

Plotly 인터랙티브 플롯

Plotly Express가 인터랙티브 차트(호버 툴팁, 줌, 팬)를 만듭니다. 대시보드와 비기술 이해관계자와의 인사이트 공유에 좋습니다. API가 seaborn을 미러링합니다(DataFrame 전달, 컬럼을 미학으로 매핑). write_html이 자기 완결 인터랙티브 HTML 파일을 저장합니다. 수백만 점의 순수 성능에는 datashader를 고려하고, 다듬기에는 Plotly가 탁월합니다.

pandas
import plotly.express as px

# Interactive scatter (hover, zoom, pan)
fig = px.scatter(df, x="age", y="score", color="city",
                 hover_data=["name"], title="Score vs Age")
fig.show()

# Line chart
fig = px.line(df, x="date", y="score", color="city")

# Bar
fig = px.bar(df, x="city", y="score", color="pass", barmode="group")

# Histogram
fig = px.histogram(df, x="score", color="city", marginal="box")

# Faceted
fig = px.scatter(df, x="age", y="score", facet_col="city")

# 3D
fig = px.scatter_3d(df, x="age", y="score", z="hours", color="city")

# Save as HTML (interactive, no JS needed to view)
fig.write_html("plot.html")

서브플롯과 레이아웃

plt.subplots가 축 격자를 만들며 플롯 시 ax=로 각각 전달하세요. sharex/sharey가 서브플롯 간 축을 정렬합니다(스케일 비교에 유용). secondary_y가 다른 y축에 두 번째 시리즈를 플롯합니다(예: 가격과 거래량). tight_layout이 레이블 겹침을 막습니다. 복잡한 레이아웃은 gridspec이 서브플롯 크기의 더 세밀한 제어를 줍니다.

pandas
import matplotlib.pyplot as plt

# pandas plot on specific axes
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
df["age"].plot.hist(ax=axes[0, 0], title="Age")
df["score"].plot.hist(ax=axes[0, 1], title="Score")
df["city"].value_counts().plot.bar(ax=axes[1, 0], title="City")
df.plot.scatter(x="age", y="score", ax=axes[1, 1], title="Age vs Score")
plt.tight_layout(); plt.show()

# Shared x-axis
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(10, 6))
df["score"].plot(ax=ax1)
df["age"].plot(ax=ax2)

# Secondary y-axis
ax = df["score"].plot()
df["age"].plot(ax=ax, secondary_y=True)
ax.set_ylabel("Score"); ax.right_ax.set_ylabel("Age")

DataFrame 스타일링

Styler 객체가 Jupyter와 HTML에서의 DataFrame 렌더링을 커스터마이징합니다. 그래디언트, 셀 안 막대, 조건 서식으로 표가 한눈에 읽힙니다. format이 숫자 표시(소수, 백분율)를 제어합니다. 스타일링은 표시 시 계산되며(데이터를 바꾸지 않음) 보고서용 HTML로 내보낼 수 있습니다. applymap은 셀별 함수를 적용하고 apply는 행/열별로 동작합니다.

pandas
# Style a DataFrame for HTML/Jupyter display
styled = df.style.highlight_max(color="lightgreen")
styled = df.style.highlight_min(color="lightcoral")
styled = df.style.background_gradient(cmap="Blues", subset=["score"])

# Bar charts inside cells
df.style.bar(subset=["score"], color="#5fba7d")

# Format numbers
df.style.format({"score": "{:.2f}", "age": "{:.0f}"})
df.style.format({"score": "{:.2%}"})  # as percentage

# Conditional formatting
def color_neg_red(val):
    color = "red" if val < 0 else "black"
    return f"color: {color}"
df.style.applymap(color_neg_red, subset=["change"])

# Combine styles
(df.style
   .format({"score": "{:.2f}"})
   .background_gradient(cmap="RdYlGn", subset=["score"])
   .set_caption("Student Scores"))

# Export to HTML
styled.to_html("table.html")
17

내보내기와 서식

표시 서식

표시 옵션이 콘솔/Jupyter에서의 pandas 출력을 제어합니다. 더 보려 max_rows/max_columns를 늘리고, 일관된 소수를 위해 float_format을 설정하세요. option_context가 (끝나면 복구하는) 설정을 임시 변경하는 컨텍스트 매니저로, 환경을 전역 바꾸지 않고 일회성 검사에 완벽합니다. 자주 쓰는 설정은 시작 스크립트에 두세요.

pandas
# Global display options
pd.set_option("display.max_rows", 100)
pd.set_option("display.max_columns", 50)
pd.set_option("display.width", 1000)
pd.set_option("display.max_colwidth", 100)
pd.set_option("display.float_format", "{:.2f}".format)

# Reset to defaults
pd.reset_option("display.max_rows")

# Float formatting only for one operation
with pd.option_context("display.float_format", "{:.2f}".format):
    print(df)

# Temporarily show more rows
with pd.option_context("display.max_rows", None):
    print(df.head(100))

다중 형식 내보내기

to_markdown이 README와 문서용 GitHub 준비 테이블을 만듭니다. to_html은 웹 페이지에 삽입되고 to_latex는 학술 논문용입니다. to_dict(orient='records')가 API용 (JSON 같은) dict의 리스트로 변환합니다. 각 형식에 옵션이 있으니 문서를 탐색하세요. Excel은 engine='openpyxl'이 서식 공식, 조건 서식, 차트를 지원합니다.

pandas
# CSV
df.to_csv("out.csv", index=False)
df.to_csv("out.tsv", sep="\t", index=False)

# Excel with formatting (needs openpyxl)
with pd.ExcelWriter("out.xlsx", engine="openpyxl") as w:
    df.to_excel(w, sheet_name="data", index=False)
    summary.to_excel(w, sheet_name="summary")

# Markdown (great for docs/reports)
print(df.to_markdown(index=False))
df.to_markdown("table.md", index=False)

# HTML
df.to_html("table.html", index=False, classes="table")

# LaTeX
print(df.to_latex(index=False, caption="Results"))

# JSON
df.to_json("out.json", orient="records", indent=2, date_format="iso")

# Dict / records
df.to_dict(orient="records")  # list of dicts
df.to_dict(orient="list")     # dict of lists

클립보드와 문자열

to_clipboard(excel=True)는 Excel/Google Sheets에 바로 붙여 넣을 수 있는 탭 구분 테이블을 복사합니다. Python과 스프레드시트 사이 데이터 이동에 놀랍도록 편리합니다. read_clipboard는 그 반대로 웹페이지나 스프레드시트에서 테이블을 복사한 뒤 파일 저장 없이 DataFrame으로 읽습니다. to_string이 로깅용 평문 표현을 줍니다.

pandas
# Copy a DataFrame to the clipboard (paste into Excel/Sheets)
df.to_clipboard(index=False, excel=True)

# Read from clipboard (paste a table from a spreadsheet/webpage)
df = pd.read_clipboard()

# Convert to string with formatting
print(df.to_string(index=False))
print(df.to_string(max_rows=10))

# Pretty-print in Jupyter
from IPython.display import display
display(df.head(10))

# Render a Series as a string
print(s.to_string())

# Quick peek at value (useful in debugging)
df.head().to_dict("records")

Excel 서식

openpyxl로 Excel 출력을 프로그래밍 방식으로 스타일링할 수 있습니다. 굵은 헤더, 컬럼 폭, 틀 고정, 조건 서식, 공식. 쓴 뒤 writer.book으로 워크북에, writer.sheets로 시트에 접근합니다. 컬럼 자동 크기 조절은 수동 폭 계산이 필요합니다(Excel이 파일 쓰기 시 자동으로 안 함). 틀 고정은 스크롤 중 헤더를 보이게 합니다.

pandas
from openpyxl.styles import Font, PatternFill
from openpyxl.utils import get_column_letter

# Write with conditional formatting
with pd.ExcelWriter("report.xlsx", engine="openpyxl") as writer:
    df.to_excel(writer, sheet_name="Data", index=False)

    # Access the workbook to style
    wb = writer.book
    ws = writer.sheets["Data"]

    # Bold header
    for cell in ws[1]:
        cell.font = Font(bold=True, color="FFFFFF")
        cell.fill = PatternFill("solid", fgColor="4472C4")

    # Auto-size columns
    for col in ws.columns:
        max_len = max(len(str(c.value)) for c in col if c.value is not None)
        ws.column_dimensions[get_column_letter(col[0].column)].width = max_len + 2

    # Freeze header row
    ws.freeze_panes = "A2"

재현 가능한 노트북

노트북 헤더 표준화(임포트, 옵션, seed, 버전 확인)가 분석을 재현 가능하게 하고 디버깅 시간을 아낍니다. pd.show_versions()가 pandas/numpy/python 버전을 보고하므로 버그 보고에 붙여 넣으세요. shape, dtype, head, 결측을 출력하는 check_df 헬퍼가 새 데이터셋 첫 검토를 표준화합니다. 경고는 특정 카테고리만 억제하세요. 전부는 절대 아닙니다.

pandas
# At the top of every analysis notebook
import pandas as pd
import numpy as np
pd.set_option("display.max_columns", None)
pd.set_option("display.float_format", "{:.4f}".format)

# Set a seed for reproducibility
np.random.seed(42)

# Show versions for reproducibility
pd.show_versions()

# Common imports grouped
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme(style="whitegrid")

# Suppress chained-assignment warnings cleanly
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)

# Validate data on load
def check_df(df, name="df"):
    print(f"=== {name} ===")
    print(f"Shape: {df.shape}")
    print(df.dtypes)
    print(df.head())
    print(df.isnull().sum())
check_df(df)
18

흔한 함정

SettingWithCopyWarning

SettingWithCopyWarning은 pandas가 '할당이 유지되지 않을 수 있다'고 알리는 것입니다. 체이닝 인덱싱(df[mask]['col']=x)은 임시 복사본을 수정할 수 있습니다. 해법은 조건 할당에 항상 .loc[row_mask, col_name] = value입니다. 서브셋 후 수정할 때는 명시적으로 .copy()를 쓰세요. 개발 중에는 경고를 'raise'로 두어 버그를 오류로 잡으세요.

pandas
# BAD: chained indexing — may not modify df
df[df["age"] > 30]["city"] = "NYC"   # SettingWithCopyWarning

# GOOD: single .loc assignment
df.loc[df["age"] > 30, "city"] = "NYC"

# When subsetting, be explicit about copy vs view
subset = df[df["age"] > 30].copy()   # explicit copy
subset["city"] = "NYC"               # safe — modifies subset only

# Detect the warning
pd.set_option("mode.chained_assignment", "warn")   # default
pd.set_option("mode.chained_assignment", "raise")  # error (dev mode)
pd.set_option("mode.chained_assignment", None)     # suppress

# Rule: if you're going to modify, use .loc or .copy() first

인덱스 정렬의 놀라움

인덱스 정렬이 pandas의 슈퍼파워이자 가장 큰 함정입니다. Series를 컬럼에 할당하면 pandas가 위치가 아니라 인덱스로 매칭하므로, Series의 인덱스가 다르면 NaN이나 잘못된 값을 얻습니다. 위치로 할당하려 .values를 쓰거나 먼저 reset_index로 인덱스를 정렬하세요. 이 버그는 조용합니다(경고 없음) 가장 흔한 pandas 실수 중 하나입니다.

pandas
# Adding Series aligns on index — NaN where they don't match
s1 = pd.Series([1, 2, 3], index=["a", "b", "c"])
s2 = pd.Series([10, 20, 30], index=["b", "c", "d"])
s1 + s2
# a     NaN
# b    12.0
# c    33.0
# d     NaN

# When assigning a Series to a column, alignment happens by index
df["new"] = some_series   # rows matched by INDEX, not position!

# To force positional alignment, use .values
df["new"] = some_series.values   # assign by position

# After sorting/resetting, indexes may not match
df1 = df.sort_values("age")
df1["rank"] = range(len(df1))   # WRONG if index isn't 0..n-1
df1["rank"] = np.arange(len(df1))  # also WRONG — aligns on index
df1["rank"] = pd.Series(range(len(df1)), index=df1.index)  # correct
# Or simply:
df1 = df1.reset_index(drop=True)
df1["rank"] = range(len(df1))

inplace vs 재할당

pandas 커뮤니티는 inplace=True에서 함수형 재할당으로 옮겨가고 있습니다. 메서드 체이닝(읽기 좋은 파이프라인)을 가능하게 하고 더 예측 가능합니다. inplace는 (pandas가 어차피 복사하는 경우가 많아) 거의 메모리를 아끼지 못합니다. 체이닝 스타일(df.method().method().method())이 위에서 아래로 읽히는 현대 관용구입니다. inplace는 실제 메모리 이득을 측정했을 때만 쓰세요.

pandas
# Two equivalent styles:
df = df.sort_values("age")        # reassign (returns new df)
df.sort_values("age", inplace=True)  # modify in place

# Most pandas methods return a new object (functional style).
# inplace=True modifies the object — but:
# 1. It's being deprecated in some methods
# 2. It can prevent method chaining
# 3. It sometimes still makes a copy under the hood

# Prefer functional style for chaining:
(df
   .sort_values("age")
   .reset_index(drop=True)
   .rename(columns={"old": "new"}))

# inplace is fine for memory savings on huge DataFrames,
# but rarely matters otherwise.

가변 기본 인자

행별 DataFrame 성장(루프의 df.append나 pd.concat)은 O(n²)입니다. append마다 전체 프레임을 복사합니다. 항상 행을 리스트로 모은 뒤 DataFrame을 한 번 만드세요. Python의 가변 기본 인자(리스트, dict)에도 같은 것이 적용됩니다. 호출 간 공유되는 고전적 Python 버그입니다. None을 센티널로 쓰고 함수 안에서 초기화하세요.

pandas
# BAD: default mutable args are shared across calls
def add_row(df, new_data=[]):   # NEVER use mutable defaults
    new_data.append(1)
    return df

# GOOD: use None
def add_row(df, new_data=None):
    if new_data is None:
        new_data = []
    ...

# Building a DataFrame row by row (SLOW — anti-pattern)
df = pd.DataFrame()
for item in items:
    df = pd.append(df, item)  # deprecation + O(n^2)

# GOOD: build a list of records, then construct once
records = []
for item in items:
    records.append({"name": item.name, "value": item.value})
df = pd.DataFrame(records)

# Or use from_records
df = pd.DataFrame.from_records(items, columns=["name", "value"])

NaN 전파

NaN은 자기 자신과 절대 같지 않습니다(NaN == NaN은 False). 결측 감지에는 ==가 아니라 isna()를 쓰세요. 기본 집계는 NaN을 건너뛰지만(sum, mean) 전파는 skipna=False입니다. NaN이 하나라도 있는 정수 컬럼은 float64로 승격됩니다(numpy 정수는 NaN을 못 담음). NaN과 함께 정수를 유지하려 nullable 'Int64' dtype(대문자 I)을 쓰세요.

pandas
# NaN propagates through most operations
np.nan + 1          # nan
np.nan > 0          # False
pd.Series([1, 2, np.nan]).sum()    # 3.0 (skips NaN by default)
pd.Series([1, 2, np.nan]).mean()   # 1.5

# Some operations DON'T skip NaN
pd.Series([1, 2, np.nan]).sum(skipna=False)  # nan

# Comparisons with NaN are always False
pd.Series([1, np.nan]) == pd.Series([1, np.nan])
# [True, False]  — NaN != NaN!

# Check for NaN correctly
s.isna()            # True for NaN
s.isnull()          # alias
s == np.nan         # WRONG — always False!
s.fillna(0) == 0    # check after filling

# Integer columns with NaN become float
s = pd.Series([1, 2, None])   # becomes float64: [1.0, 2.0, NaN]
# Use nullable Int64 to keep integer with NaN
s = pd.Series([1, 2, None], dtype="Int64")
19

실무 패턴

EDA 템플릿

표준화된 EDA 함수는 모델링 전 항상 shape, dtype, 결측, 분포, 중복을 확인하게 합니다. 잘못된 dtype(문자열로 된 숫자), 숨은 결측(-999 같은 센티널 값), 예상치 못한 중복을 일찍 잡으면 이후 수 시간의 디버깅을 아낍니다. 새 데이터셋의 첫 단계로 이것을 실행하세요.

pandas
import pandas as pd
import numpy as np

def eda(df, name="df"):
    print(f"=== {name} ===")
    print(f"Shape: {df.shape}")
    print("\n--- dtypes ---")
    print(df.dtypes)
    print("\n--- head ---")
    print(df.head())
    print("\n--- missing ---")
    print(df.isnull().sum())
    print("\n--- numeric summary ---")
    print(df.describe())
    print("\n--- categorical summary ---")
    print(df.describe(include="object"))
    print("\n--- duplicates ---")
    print(f"{df.duplicated().sum()} duplicate rows")

# Usage
eda(df)

# Per-column deep dive
for col in df.columns:
    print(f"\n### {col}")
    print(f"dtype: {df[col].dtype}")
    print(f"unique: {df[col].nunique()}")
    if df[col].dtype == "object":
        print(df[col].value_counts().head(10))
    else:
        print(df[col].describe())

정제 파이프라인 구축

메서드 체이닝(.pipe / .assign / .dropna 파이프라인)은 정제를 재현 가능하고 테스트 가능하게 합니다. 각 단계가 순수 함수로 어느 시점에든 검사하기 쉽습니다. 따옴표 골칫거리를 피하려 일찍 컬럼 이름을 snake_case로 바꾸세요. 끝의 assertion이 조용한 실패(예: 모든 날짜 파싱 실패)를 잡습니다. 파이프라인을 함수로 감싸 새 데이터 배치에 재사용하세요.

pandas
def clean(df):
    """A reusable cleaning pipeline."""
    return (df
        # Standardize column names
        .rename(columns=lambda c: c.strip().lower().replace(" ", "_"))
        # Drop empty columns
        .dropna(axis=1, how="all")
        # Parse dates
        .assign(date=lambda d: pd.to_datetime(d["date"], errors="coerce"))
        # Numeric coercion
        .assign(amount=lambda d: pd.to_numeric(d["amount"], errors="coerce"))
        # Fill missing
        .fillna({"category": "unknown"})
        # Dedupe
        .drop_duplicates()
        # Reset index
        .reset_index(drop=True)
    )

df_clean = clean(df_raw)

# Verify
assert df_clean["date"].notnull().all(), "Some dates failed to parse"
assert len(df_clean) <= len(df_raw), "Cleaning should not add rows"

피벗 테이블 분석

pivot_table이 분석가의 만능 칼입니다. totals에는 margins=True와 결합하고, 즉각적 통찰에는 히트맵과 결합하세요. 역(melt)은 추가 처리를 위해 다시 tidy 긴 형식으로 되돌립니다. ('그룹별 top N' 패턴(정렬 후 groupby head))은 비즈니스 보고서에서 극히 흔합니다.

pandas
# Multi-dimensional analysis in one shot
pivot = pd.pivot_table(
    df,
    values="revenue",
    index=["region", "product"],
    columns=["quarter"],
    aggfunc="sum",
    fill_value=0,
    margins=True,         # add row/column totals
    margins_name="Total",
)

# Heatmap of the pivot
import seaborn as sns
sns.heatmap(pivot, annot=True, fmt=".0f", cmap="YlGnBu")

# Convert back to long
long = pivot.reset_index().melt(
    id_vars=["region", "product"],
    var_name="quarter",
    value_name="revenue",
)

# Top product per region
top = (df
    .groupby(["region", "product"])["revenue"].sum()
    .reset_index()
    .sort_values("revenue", ascending=False)
    .groupby("region").head(1))

ML을 위한 피처 엔지니어링

피처 엔지니어링에서 도메인 지식과 pandas가 만납니다. 엔티티별 집계(고객 생애 지출), 비율(월별 지출), 시간 기반 피처(재직 기간), binned 범주형. 집계된 피처를 엔티티 ID로 메인 프레임에 다시 병합하세요. 선형 모델용 원-핫 인코딩은 get_dummies입니다. 학습과 추론 시점에 같은 변환이 적용되도록 함수로 감싸세요.

pandas
def add_features(df):
    """Add features for a churn model."""
    out = df.copy()

    # Time-based features
    out["tenure_years"] = out["tenure_months"] / 12
    out["is_new_customer"] = (out["tenure_months"] < 12).astype(int)

    # Aggregations per customer (need transaction history)
    # txns is a separate transactions DataFrame
    agg = txns.groupby("customer_id").agg(
        total_spend=("amount", "sum"),
        txn_count=("amount", "count"),
        avg_txn=("amount", "mean"),
        last_txn_date=("date", "max"),
    ).reset_index()
    out = out.merge(agg, on="customer_id", how="left")

    # Ratio features
    out["spend_per_month"] = out["total_spend"] / out["tenure_months"]

    # Binning
    out["age_group"] = pd.cut(out["age"], bins=[0,25,40,60,100],
                              labels=["young","adult","mid","senior"])

    # Encode categoricals
    out = pd.get_dummies(out, columns=["age_group", "plan"], drop_first=True)

    return out

df_ml = add_features(df)

지저분한 CSV 읽기

실제 CSV는 지저분합니다. 잘못된 인코딩(utf-8 실패 시 latin-1이나 cp1252 시도), 유럽식 소수 콤마(decimal=','), 헤더 전 메타데이터 행(skiprows), 센티널 null 값(na_values). usecols는 필요한 컬럼만 로드해 넓은 파일에서 메모리를 아낍니다. 무작정 읽기 전에 낯선 CSV의 앞 몇 줄을 텍스트 편집기로 항상 확인하세요.

pandas
# Common CSV issues and fixes

# Bad encoding
df = pd.read_csv("data.csv", encoding="latin-1")  # or utf-8-sig, cp1252

# Wrong separator
df = pd.read_csv("data.tsv", sep="\t")
df = pd.read_csv("data.csv", sep=";", decimal=",")  # European format

# Skip metadata rows at the top
df = pd.read_csv("data.csv", skiprows=3)

# Multiple header rows
df = pd.read_csv("data.csv", header=[0, 1])

# Custom NA values
df = pd.read_csv("data.csv", na_values=["?", "N/A", "NULL", -999])

# Parse dates with multiple formats
df = pd.read_csv("data.csv", parse_dates=["date"], dayfirst=True)

# Only load specific columns (saves memory)
df = pd.read_csv("data.csv", usecols=["id", "date", "amount"])

# Handle quoted fields with commas/newlines
df = pd.read_csv("data.csv", quotechar='"', escapechar="\\")
20

윈도우 연산 심화

커스텀 함수를 곁들인 Rolling

내장 rolling 집계(mean, std, median, quantile)는 C 최적화로 빠릅니다. 커스텀 apply 함수는 유연하지만 느립니다(윈도우마다 Python 콜백). 가중 평균이나 회귀에는 numpy 연산을 안에 넣은 apply를 쓰세요. raw=True(기본)가 numpy 배열을 전달하고(빠름) raw=False는 인덱스가 필요하면 Series를 전달합니다.

pandas
s = pd.Series(range(20), dtype=float)

# Built-in aggregations (fast, C-optimized)
s.rolling(5).mean()
s.rolling(5).std()
s.rolling(5).median()
s.rolling(5).quantile(0.75)
s.rolling(5).sum()

# Custom function (slower, but flexible)
s.rolling(5).apply(lambda x: x.max() - x.min())

# Weighted rolling average
weights = np.array([0.1, 0.2, 0.3, 0.25, 0.15])
s.rolling(5).apply(lambda x: np.dot(x, weights))

# Rolling regression (slope over window)
def slope(x):
    return np.polyfit(range(len(x)), x, 1)[0]
s.rolling(10).apply(slope)

# raw=False passes Series (with index) to the function
s.rolling(5).apply(lambda x: x.iloc[-1] / x.iloc[0], raw=False)

시간 기반 윈도우

시간 기반 윈도우('7D')는 불규칙 표본 데이터를 올바르게 처리합니다. 고정 행 수가 아니라 시간 범위 내 모든 점을 포함합니다. 갭이 있는 실제 시계열에 필수입니다. center=True가 윈도우를 현재 점에 중심 둡니다(스무딩에 유용). closed='left'가 현재 점을 제외해 ('미래'에서 피처 계산 시 누수 방지).

pandas
# Row-count vs time-based windows
ts = pd.Series(range(100), index=pd.date_range("2024-01-01", periods=100, freq="D"))

# Row-count: exactly 7 rows (may span more than 7 days if data is irregular)
ts.rolling(7).mean()

# Time-based: all rows within the last 7 days (handles gaps)
ts.rolling("7D").mean()

# Time-based is essential for irregular time series
irregular = pd.Series([1, 2, 3],
    index=pd.to_datetime(["2024-01-01", "2024-01-05", "2024-01-15"]))
irregular.rolling("7D").sum()   # 1, 3, 3 (third is just itself, no neighbors in 7d)

# Center the window
ts.rolling("7D", center=True).mean()  # window centered on current point

# Closed controls which endpoints are included
ts.rolling("7D", closed="left").mean()  # exclude current point

Expanding과 EWMA

expanding이 시작부터 현재 점까지의 모든 데이터 위에서 통계를 계산합니다. 누적 벤치마크와 실행 극단값에 유용합니다. ewm(지수 가중)이 최근 관측에 더 가중하며 금융 스무딩(EWMA)의 표준입니다. span이 직관적입니다(N기간 이동 평균과 유사), alpha가 원시 스무딩 인자입니다. EWMA가 단순 이동 평균보다 최근 변화에 더 빨리 반응합니다.

pandas
s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8], dtype=float)

# Expanding: window grows from the start
s.expanding(min_periods=2).mean()   # cumulative mean
s.expanding().max()                 # running maximum
s.expanding().std()

# Exponentially weighted moving average
s.ewm(span=5).mean()       # span=N similar to N-period moving avg
s.ewm(alpha=0.3).mean()    # alpha = smoothing factor (0-1)
s.ewm(halflife=3).mean()   # halflife: weight halves every N periods

# EWMA volatility (finance)
returns.ewm(span=20).std()  # 20-period EWMA volatility

# Relationship: span = (2/alpha) - 1
# Higher alpha/span = more responsive to recent data

누적 연산

cumsum, cummax, cummin, cumprod가 직접 누적 메서드이며 흔한 경우 expanding보다 빠릅니다. groupby와 결합하면 그룹별 누계(예: 고객별 잔액 변화)를 계산합니다. 불리언 조건의 cumsum 트릭이 세션/세그먼트 식별자를 만들며 시계열을 이벤트 사이의 에피소드로 나누는 데 유용합니다.

pandas
s = pd.Series([1, 2, 3, 4, 5])

# Direct cumulative methods (faster than expanding)
s.cumsum()    # [1, 3, 6, 10, 15]
s.cummax()    # [1, 2, 3, 4, 5]
s.cummin()    # [1, 1, 1, 1, 1]
s.cumprod()   # [1, 2, 6, 24, 120]

# Cumulative within groups
df["running_total"] = df.groupby("customer")["amount"].cumsum()
df["rank_in_group"] = df.groupby("customer")["amount"].rank(ascending=False)
df["pct_of_total"] = df["amount"] / df.groupby("customer")["amount"].transform("sum")

# Cumulative count of condition
df["days_since_event"] = (df["event"] == 1).cumsum()
df["event_number"] = df.groupby(
    (df["event"] == 1).cumsum()
).cumcount()

다중 출력 Rolling Apply

여러 rolling 통계는 각각 따로 계산하는 것이(window.mean(), window.std()) Series를 반환하는 단일 apply보다 명확하고 종종 빠릅니다. rolling 분위수로 추세 주변의 신뢰 밴드(q10/q90)를 만들 수 있습니다. rolling 통계의 DataFrame 만들기가 플롯이나 ML 모델 입력 전의 전형 패턴입니다.

pandas
# Apply a function returning multiple values per window
def rolling_stats(x):
    return pd.Series({
        "mean": x.mean(),
        "std": x.std(),
        "min": x.min(),
        "max": x.max(),
    })

stats = s.rolling(10).apply(rolling_stats, raw=False)
# This creates a DataFrame with one row per window, columns = the Series index

# Alternative: compute each separately (often clearer)
window = s.rolling(10)
result = pd.DataFrame({
    "mean": window.mean(),
    "std":  window.std(),
    "min":  window.min(),
    "max":  window.max(),
})

# Rolling quantiles
q = pd.DataFrame({
    "q10": s.rolling(20).quantile(0.1),
    "q50": s.rolling(20).quantile(0.5),
    "q90": s.rolling(20).quantile(0.9),
})

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.