教程 / Python3 / Pandas 抽样与随机数据

Pandas 抽样与随机数据

Pandas 抽样与随机数据 Pandas 提供了丰富的随机抽样功能,可以从数据集中按要求随机选取样本,也支持生成随机数据。 随机抽样 sample 方法 实例 import pandas as pd import nu

Pandas 提供了丰富的随机抽样功能,可以从数据集中按要求随机选取样本,也支持生成随机数据。


随机抽样

sample 方法

实例

import pandas as pd
import numpy as np

# 创建大数据集
df = pd.DataFrame({
    "ID": range(1, 1001),
    "值": np.random.randn(1000)
})

# 随机抽取5行
print("随机抽取5行:")
print(df.sample(5))
print()

# 抽取30%的数据
print("随机抽取30%:")
print(df.sample(frac=0.3))
print()

# 可重复抽样
print("可重复抽样5行:")
print(df.sample(5, replace=True))

设置随机种子

实例

import pandas as pd
import numpy as np

# 设置随机种子,保证结果可复现
np.random.seed(42)

df = pd.DataFrame({
    "ID": range(1, 11),
    "值": np.random.randn(10)
})

print("使用随机种子42:")
print(df.sample(3))

# 再次运行相同种子,得到相同结果
print("\n再次运行相同种子:")
np.random.seed(42)
print(df.sample(3))

随机数据生成

实例

import pandas as pd
import numpy as np

# 生成随机整数
print("随机整数 [0, 10):")
print(pd.Series(np.random.randint(0, 10, 5)))
print()

# 生成随机浮点数
print("随机浮点数 [0, 1):")
print(pd.Series(np.random.random(5)))
print()

# 生成正态分布随机数
print("正态分布 N(0, 1):")
print(pd.Series(np.random.randn(5)))
print()

# 指定均值和标准差
print("正态分布 N(10, 2):")
print(pd.Series(np.random.normal(10, 2, 5)))
print()

# 随机选择
choices = ["A", "B", "C", "D"]
print("随机选择:")
print(pd.Series(np.random.choice(choices, 10)))

训练测试集划分

实例

import pandas as pd
import numpy as np

# 模拟数据集
df = pd.DataFrame({
    "特征1": np.random.randn(100),
    "特征2": np.random.randn(100),
    "目标": np.random.choice([0, 1], 100)
})

# 划分训练集和测试集 (80% / 20%)
train = df.sample(frac=0.8, random_state=42)
test = df.drop(train.index)

print(f"训练集: {len(train)} 行")
print(f"测试集: {len(test)} 行")
print()

# 分层抽样(保持目标变量比例)
print("分层抽样:")
from sklearn.model_selection import train_test_split
# 需要安装 scikit-learn: pip install scikit-learn
# train, test = train_test_split(df, test_size=0.2, stratify=df["目标"])