如何从DataFrame中选择确切数量的随机行

时间:2016-11-06 20:44:43

标签: apache-spark random spark-dataframe

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

1 个答案:

答案 0 :(得分:2)

一种可能的方法是使用.count()计算行数,然后使用sample()的{​​{3}}中的python生成任意长度的随机序列范围。最后使用生成的数字列表vals来对索引列进行子集化。

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|
+---+---+