首页 > 解决方案 > 如何随机采样 DataFrame 中的一小部分行?

问题描述

我正在尝试使用 collect 函数将数据框作为记录列表获取,对于具有 4000 多列的数据框来说它非常慢。有更快的替代方案吗?我什至尝试在调用 .collect() 之前执行 df.persist() ,但即便如此也无济于事。

val data = df
  .collect()
  .map(
    x ⇒
      x.toSeq.toList.map(_ match {
        case null  ⇒ ""
        case other ⇒ other.toString
      })
  )
  .toList

编辑(来自评论):

所以用例是从数据框中获取记录并将它们显示为示例数据。

标签: scaladataframeapache-sparkcollect

解决方案


根据您的问题和评论,听起来您正在寻找一种对列和行进行采样的方法。这是一种简单的方法,可以在 DataFrame 中随机抽取 N 个随机列和sample一小部分行:

val df = Seq(
  (1, "a", 10.0, 100L),
  (2, "b", 20.0, 200L),
  (3, "c", 30.0, 300L)
).toDF("c1", "c2", "c3", "c4")

import scala.util.Random

// e.g. Take 3 random columns and randomly pick ~70% of rows
df.
  select(Random.shuffle(df.columns.toSeq).take(3).map(col): _*).
  sample(70.0/100).
  show
// +---+---+---+
// | c1| c2| c4|
// +---+---+---+
// |  1|  a|100|
// |  3|  c|300|
// +---+---+---+

推荐阅读