sample()函数常用来随机获取dataFrame中数据,可以用于快速查看。

常用的有以下入参:

  • n :指定获取的数量,默认为1
  • axis:指定随机获取的是行还是列。0表示行,1表示列,默认为0
  • weitghts:指定权重信息,需要与 行或者列的数目相等,为列表
  • frac:百分比,随机获取的百分比比重

下面举例:

>>> 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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。