본문으로 건너뛰기
김신건의 로그

[Pandas] sample

· 수정 · 📖 약 1분 · 199자/단어 #python #pandas #sample #random
Pandas sample, DataFrame.sample, random sampling

정의

DataFrame.sample(n=, frac=) 는 행/열을 랜덤 샘플링. 빠른 탐색, train/test split, 데이터 검증에 자주 사용.

기본

df.sample(n=5)                        # 5 개 무작위
df.sample(frac=0.1)                    # 10% 무작위
df.sample(n=5, random_state=42)        # 재현 가능 (시드)

주요 옵션

옵션의미
n샘플 개수
frac비율 (0-1)
replace복원 추출 (기본 False)
weights가중치 컬럼 / Series
random_state시드
axis0 (행) / 1 (열)

복원 추출 (bootstrap)

df.sample(n=len(df), replace=True, random_state=42)
# bootstrap 한 번

가중 샘플링

# 가중치 컬럼 기반
df.sample(n=100, weights='priority')

# 명시적 weights
weights = df['vip'].map({True: 5, False: 1})
df.sample(n=100, weights=weights)

VIP 가 5 배 자주 샘플링.

train / test split

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

sklearn.model_selection.train_test_split 가 더 명시적이지만 빠르게 할 때 pandas 만으로 가능.

groupby + sample (stratified sampling)

# 각 클래스에서 100 개씩
df.groupby('class').sample(n=100, random_state=42)

# 각 클래스에서 10% 씩
df.groupby('class').sample(frac=0.1, random_state=42)

ignore_index

df.sample(n=10, ignore_index=True)   # index 0, 1, ..., 9 로 재배치

자주 쓰는 패턴

EDA 빠르게

df.sample(20)        # 20 행만 보면서 데이터 형태 확인

Imbalanced data 다운샘플

majority = df[df['class'] == 0].sample(n=len(df[df['class'] == 1]), random_state=42)
minority = df[df['class'] == 1]
balanced = pd.concat([majority, minority]).sample(frac=1)   # 섞기

Bootstrap 통계

samples = [df.sample(frac=1, replace=True)['x'].mean() for _ in range(1000)]
np.percentile(samples, [2.5, 97.5])    # 95% CI

numpy 와의 비교

import numpy as np
np.random.choice(df.index, size=100, replace=False)   # index 만
df.sample(n=100)                                       # DataFrame

pandas API 가 더 자연스러움.

함정

1. random_state 빠뜨림

df.sample(n=5)            # 매 실행마다 다른 결과
df.sample(n=5, random_state=42)   # 같은 결과 (재현)

테스트, ML 실험에는 시드 필수.

2. frac > 1 + replace=False

df.sample(frac=2)           # ❌ ValueError (행 수보다 큼)
df.sample(frac=2, replace=True)   # ✓ 복원 추출이면 가능

3. groupby + sample 의 random_state

df.groupby('class').sample(n=10, random_state=42)
# 각 그룹의 시드는 다를 수 있음 (pandas 버전 의존)

참고

💬 댓글

사이트 검색 / 명령어

검색

스크롤 = 확대/축소 · 드래그 = 이동 · 0 = 원래 크기 · ESC = 닫기