如何随机抽取 DataFrame 中的一小部分行?

How to randomly sample a fraction of the rows in a DataFrame?

我正在尝试使用 collect 函数将数据框作为记录列表获取,但对于包含 4000 多列的数据框来说速度非常慢。有没有更快的选择?我什至尝试在调用 .collect() 之前执行 df.persist() 但即使这样也无济于事。

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

编辑(来自评论):

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

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

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

您应该限制驱动程序获取的行数,collect 将获取所有内容。

要么使用

df.limit(20).collect

df.take(20)

此外,如果您先将 Row 映射到 List[String] 然后收集,我应该会更快。像这样,这个操作在执行器上运行:

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