如何从DataFrame中选择确切数量的随机行 [英] How to select an exact number of random rows from DataFrame

查看:994
本文介绍了如何从DataFrame中选择确切数量的随机行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何有效地从DataFrame中选择确切个随机行? 数据包含可以使用的索引列. 如果我必须使用最大大小,那么索引列上的count()或max()效率更高?

How can I select an exact number of random rows from a DataFrame efficiently? The data contains an index column that can be used. If I have to use maximum size, what is more efficient, count() or max() on the index column?

推荐答案

一种可行的方法是使用.count()计算行数,然后使用python

A possible approach is to calculate the number of rows using .count(), then use sample() from python's random library to generate a random sequence of arbitrary length from this range. Lastly use the resulting list of numbers vals to subset your index column.

import random 
def sampler(df, col, records):

  # Calculate number of rows
  colmax = df.count()

  # Create random sample from range
  vals = random.sample(range(1, colmax), records)

  # Use 'vals' to filter DataFrame using 'isin'
  return df.filter(df[col].isin(vals))

示例:

df = sc.parallelize([(1,1),(2,1),
                     (3,1),(4,0),
                     (5,0),(6,1),
                     (7,1),(8,0),
                     (9,0),(10,1)]).toDF(["a","b"])

sampler(df,"a",3).show()
+---+---+
|  a|  b|
+---+---+
|  3|  1|
|  4|  0|
|  6|  1|
+---+---+

这篇关于如何从DataFrame中选择确切数量的随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆