如何对DataFrame进行随机采样?

中等机器学习

答题要点

import pandas as pd

# 随机抽取n行
df_sample = df.sample(n=100)  # 抽100行

# 随机抽取比例
df_sample = df.sample(frac=0.1)  # 抽10%

# 可重复采样(设置随机种子)
df_sample = df.sample(n=100, random_state=42)

# 有放回抽样(Bootstrap)
df_bootstrap = df.sample(n=len(df), replace=True, random_state=42)

# 无放回抽样(默认)
df_sample = df.sample(n=100, replace=False)

# 按权重采样
weights = df['importance']  # 重要性权重
df_weighted = df.sample(n=100, weights=weights, random_state=42)

# 分层采样(保持各类别比例)
def stratified_sample(df, strat_col, n):
    """分层随机采样"""
    return df.groupby(strat_col, group_keys=False).apply(
        lambda x: x.sample(min(len(x), n), random_state=42)
    )

df_stratified = stratified_sample(df, 'category', 50)

# 或使用train_test_split
from sklearn.model_selection import train_test_split
df_sample, _ = train_test_split(df, train_size=0.1, stratify=df['label'], random_state=42)

# 采样行和列
df_sample = df.sample(n=100, axis=0).sample(n=5, axis=1)  # 100行,5列

# 打乱顺序
df_shuffled = df.sample(frac=1, random_state=42).reset_index(drop=True)

# 时间序列采样(按时间段)
df_recent = df.nlargest(1000, 'date')  # 最近1000条

# 采样后保持索引连续
df_sample = df.sample(n=100).reset_index(drop=True)

# 确保采样数不超过总数
n_sample = min(100, len(df))
df_sample = df.sample(n=n_sample)

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题