当前位置: 首页 > news >正文

【Pandas】pandas DataFrame sample

Pandas2.2 DataFrame

Reindexing selection label manipulation

方法描述
DataFrame.add_prefix(prefix[, axis])用于在 DataFrame 的行标签或列标签前添加指定前缀的方法
DataFrame.add_suffix(suffix[, axis])用于在 DataFrame 的行标签或列标签后添加指定后缀的方法
DataFrame.align(other[, join, axis, level, …])用于对齐两个 DataFrameSeries 的方法
DataFrame.at_time(time[, asof, axis])用于筛选 特定时间点 的行的方法
DataFrame.between_time(start_time, end_time)用于筛选 指定时间范围内的数据行 的方法
DataFrame.drop([labels, axis, index, …])用于从 DataFrame 中删除指定行或列的方法
DataFrame.drop_duplicates([subset, keep, …])用于删除重复行的方法
DataFrame.duplicated([subset, keep])用于检测 重复行 的方法
DataFrame.equals(other)用于比较两个 DataFrame 是否完全相等的方法
DataFrame.filter([items, like, regex, axis])用于筛选列或行标签的方法
DataFrame.first(offset)用于选取 时间序列型 DataFrame 中从起始时间开始的一段连续时间窗口 的方法
DataFrame.head([n])用于快速查看 DataFrame 前几行数据 的方法
DataFrame.idxmax([axis, skipna, numeric_only])用于查找 每列或每行中最大值的索引标签 的方法
DataFrame.idxmin([axis, skipna, numeric_only])用于查找 每列或每行中最小值的索引标签 的方法
DataFrame.last(offset)用于选取 时间序列型 DataFrame 中从最后时间点开始向前截取一段指定长度的时间窗口 的方法
DataFrame.reindex([labels, index, columns, …])用于重新索引 DataFrame 的核心方法
DataFrame.reindex_like(other[, method, …])用于将当前 DataFrame 的索引和列重新设置为与另一个对象(如另一个 DataFrame 或 Series)相同
DataFrame.rename([mapper, index, columns, …])用于重命名 DataFrame 的行索引标签或列名的方法
DataFrame.rename_axis([mapper, index, …])用于**重命名 DataFrame 的索引轴名称(index axis name)或列轴名称(column axis name)**的方法
DataFrame.reset_index([level, drop, …])用于将 DataFrame 的索引(index)重置为默认整数索引,并将原索引作为列添加回 DataFrame 中的方法
DataFrame.sample([n, frac, replace, …])用于从 DataFrame 中随机抽取样本行或列的方法

pandas.DataFrame.sample()

pandas.DataFrame.sample() 是一个用于从 DataFrame 中随机抽取样本行或列的方法。它支持按指定数量(n)或比例(frac)抽样,支持有放回或无放回抽样,并可用于数据分析、数据清洗、模型训练前的数据划分等场景。


📌 方法签名
DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None, ignore_index=False)

🔧 参数说明
参数类型说明
n整数要抽取的样本数量(不能与 frac 同时使用)
frac浮点数抽取样本占总体的比例(如 0.5 表示抽取 50% 的数据)
replacebool,默认 False是否有放回抽样(True 表示允许重复抽取)
weightsstr 或 array-like权重数组或列名,表示每行/列被抽取的概率权重
random_stateint 或 numpy.random.RandomState 实例控制随机性,确保结果可复现
axis{0/'index', 1/'columns'},默认 0指定是按行抽样还是按列抽样
ignore_indexbool,默认 False是否重置索引(抽样后的 DataFrame 使用从 0 开始的新索引)

⚠️ nfrac 不能同时使用。


✅ 返回值
  • 返回一个新的 DataFrame,包含随机抽取的样本;
  • inplace=True 不可用,必须赋值给新变量;
  • 默认保留原始索引,除非设置 ignore_index=True

🧪 示例代码及结果
示例 1:基本用法 - 随机抽取 2 行
import pandas as pddf = pd.DataFrame({'A': [1, 2, 3, 4],'B': [10, 20, 30, 40]
}, index=['x', 'y', 'z', 'w'])print("Original DataFrame:")
print(df)# 随机抽取 2 行
sampled = df.sample(n=2, random_state=42)
print("\nRandomly sampled 2 rows:")
print(sampled)
输出结果:
Original DataFrame:A   B
x  1  10
y  2  20
z  3  30
w  4  40Randomly sampled 2 rows:A   B
z  3  30
x  1  10

设置 random_state=42 可保证每次运行结果一致。


示例 2:按比例抽样(frac=0.5)
# 抽取 50% 的行
sampled_frac = df.sample(frac=0.5, random_state=42)
print("\nSampled 50% of the rows:")
print(sampled_frac)
输出结果:
Sampled 50% of the rows:A   B
z  3  30
x  1  10

示例 3:有放回抽样(replace=True)
# 从 4 行中抽取 5 行(必须允许重复)
sampled_replace = df.sample(n=5, replace=True, random_state=42)
print("\nSampled with replacement (n=5):")
print(sampled_replace)
输出结果:
Sampled with replacement (n=5):A   B
z  3  30
x  1  10
z  3  30
x  1  10
y  2  20

注意某些行出现多次。


示例 4:加权抽样(weights 参数)
# 给每一行指定不同的权重
sampled_weighted = df.sample(n=2, weights=[1, 1, 1, 10], random_state=42)
print("\nWeighted sampling (last row has higher weight):")
print(sampled_weighted)
输出结果:
Weighted sampling (last row has higher weight):A   B
w  4  40
w  4  40

因为最后一行权重最高,所以更容易被选中。


示例 5:按列抽样(axis=1)
# 随机抽取 1 列
sampled_col = df.sample(n=1, axis=1, random_state=42)
print("\nRandomly sampled 1 column:")
print(sampled_col)
输出结果:
Randomly sampled 1 column:B
x  10
y  20
z  30
w  40

示例 6:忽略原索引(ignore_index=True)
# 抽样并重置索引
sampled_ignore = df.sample(n=2, ignore_index=True, random_state=42)
print("\nSampled and reset index:")
print(sampled_ignore)
输出结果:
Sampled and reset index:A   B
0  3  30
1  1  10

🧠 应用场景
  • 数据探索:快速查看部分数据;
  • 模型训练前的数据划分:随机选取训练集/验证集;
  • 数据增强:通过有放回抽样增加样本量;
  • 测试脚本:模拟小规模数据进行调试;
  • 统计分析:进行抽样调查或蒙特卡洛模拟。

⚠️ 注意事项
  • nfrac 不能同时使用;
  • 若需要重复抽样,需设置 replace=True
  • 使用 random_state 确保结果可复现;
  • 支持按行或列抽样(通过 axis);
  • 默认保留原始索引,可通过 ignore_index=True 重置;
  • 加权抽样时注意权重和应大于 0,否则会报错。
http://www.lqws.cn/news/134227.html

相关文章:

  • 机器学习的数学基础:假设检验
  • 从上下文学习和微调看语言模型的泛化:一项对照研究
  • Linux系统iptables防火墙实验拓补
  • WES7系统深度定制全流程详解(从界面剥离到工业部署)
  • 【python】运行python程序的方式
  • 数据湖是什么?数据湖和数据仓库的区别是什么?
  • 不同视角理解三维旋转
  • macOS 上使用 Homebrew 安装redis-cli
  • CanvasGroup篇
  • dvwa9——Weak Session IDs
  • JavaSec-专题-反序列化
  • 使用osqp求解简单二次规划问题
  • LeetCode-934. 最短的桥
  • 树莓派上遇到插入耳机后显示“无输入设备”问题
  • C++课设:通讯录管理系统(vector、map协作实现)
  • MQTT协议:物联网时代的通信基石
  • 使用 LangChain 和 RAG 实现《斗破苍穹》文本问答系
  • 栈-20.有效的括号-力扣(LeetCode)
  • RAG系统中的Re-ranking引擎选择指南
  • Android SharedFlow 详解
  • Unity安卓平台开发,启动app并传参
  • 读文献先读图:GO弦图怎么看?
  • 瀚文(HelloWord)智能键盘项目深度剖析:从0到1的全流程解读
  • Vue跨层级通信
  • 华为云Flexus+DeepSeek征文|实战体验云服务器单机部署和CCE高可用的架构AI赋能
  • 「Java教案」顺序结构
  • JS手写代码篇---手写apply方法
  • Rhino
  • 项目实战——C语言扫雷游戏
  • Python数据可视化科技图表绘制系列教程(二)