scala - 如何随机采样 DataFrame 中的一小部分行?
问题描述
我正在尝试使用 collect 函数将数据框作为记录列表获取,对于具有 4000 多列的数据框来说它非常慢。有更快的替代方案吗?我什至尝试在调用 .collect() 之前执行 df.persist() ,但即便如此也无济于事。
val data = df
.collect()
.map(
x ⇒
x.toSeq.toList.map(_ match {
case null ⇒ ""
case other ⇒ other.toString
})
)
.toList
编辑(来自评论):
所以用例是从数据框中获取记录并将它们显示为示例数据。
解决方案
根据您的问题和评论,听起来您正在寻找一种对列和行进行采样的方法。这是一种简单的方法,可以在 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|
// +---+---+---+
推荐阅读
- php - 如何通过 php 按 mongodb 上的嵌套对象排序?
- html - 我如何在当前代码中获取子菜单?
- svn - SVN:// 协议在迁移 authz 文件的活动目录后停止工作
- java - @RequestBody 不将请求解析为对象进行验证
- azure-devops - 一次分组和触发多个 Azure 管道
- ios - 在 iOS 11 中应用被用户杀死时的地理围栏
- node.js - 在邮递员数组中发送对象数组始终为空
- python - 我的增强拓扑实现的神经进化无法解决 XOR 问题
- audio - AWS EC2实例上的Pyaudio“无效输入设备(无默认输出设备)”
- ionic3 - 离子范围组件中的自定义事件发射器无法用于生产