pandas DataFrame.sample() 方法详解与实战示例

林见深
林见深
发布时间:2026-10-15 | 3人浏览过
原创

本文详细介绍 pandas 中 DataFrame.sample() 函数的用法,涵盖 n、axis、weights 和 frac 等关键参数。通过具体代码示例演示如何随机获取行、列、指定数量或按比例抽样,帮助开发者快速掌握数据随机采样技巧。

pandas DataFrame.sample() 函数概述

在 pandas 库中,sample() 函数主要用于从 DataFrame 中随机抽取数据,这一功能常用于快速预览数据内容或进行初步的数据探索。

sample() 核心参数解析

该函数支持多种参数配置,以满足不同的抽样需求。

  • n 参数用于指定随机抽取的具体数量,其默认值为 1。
  • axis 参数用于定义抽样的维度,0 代表对行进行随机抽取,1 代表对列进行随机抽取,默认值为 0。
  • weights 参数用于指定权重信息,该参数需传入一个列表,且列表长度必须与参与抽样的行或列数量保持一致。
  • frac 参数用于指定随机抽取的比例,即从数据中按百分比进行抽样。

随机抽样代码示例

以下通过具体代码示例展示 sample() 函数的实际应用效果。

>>> df
     name  score grade
id                    
a     bog     45     A
c   jiken     67     B
d     bob     23     A
b   jiken     34     B
f    lucy     98     A
e    tidy     75     B

# 随机获取某一行
>>> df.sample()
    name  score grade
id                   
f   lucy     98     A

# 随机获取某一列
>>> df.sample(axis=1)
    score
id       
a      45
c      67
d      23
b      34
f      98
e      75

# 随机获取3行
>>> df.sample(n=3)
     name  score grade
id                    
a     bog     45     A
b   jiken     34     B
d     bob     23     A

# 按百分比获取
>>> df.sample(frac=0.25)
     name  score grade
id                    
b   jiken     34     B
d     bob     23     A

# 设置每行的权重并随机获取两行
>>> df.sample(n=2, weights=[0.1, 0.2, 0.3, 0.1, 0.1, 0.1])
    name  score grade
id                   
e   tidy     75     B
d    bob     23     A

以上就是关于 pandas DataFrame.sample() 函数的详细介绍,更多相关 pandas 使用技巧请查阅本站历史文章或继续浏览后续内容,感谢大家的支持。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表