如何使用相等的记录分割Spark数据框 [英] How to split a spark dataframe with equal records
本文介绍了如何使用相等的记录分割Spark数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用df.randomSplit(),但它没有分成相等的行.我还有其他方法可以实现吗?
I am using df.randomSplit() but it is not splitting into equal rows. Is there any other way I can achieve it?
推荐答案
在我的情况下,我需要平衡(相等大小)的分区才能执行特定的交叉验证实验.
In my case I needed balanced (equal sized) partitions in order to perform a specific cross validation experiment.
为此,您通常:
- 随机化数据集
- 应用模运算将每个元素分配给一个折叠(分区)
完成此步骤后,您将必须使用filter
提取每个分区,但afaik仍然没有将单个RDD分成多个分区的转换.
After this step you will have to extract each partition using filter
, afaik there is still no transformation to separate a single RDD into many.
这是scala中的一些代码,它仅使用标准的spark操作,因此应易于适应python:
Here is some code in scala, it only uses standard spark operations so it should be easy to adapt to python:
val npartitions = 3
val foldedRDD =
// Map each instance with random number
.zipWithIndex
.map ( t => (t._1, t._2, new scala.util.Random(t._2*seed).nextInt()) )
// Random ordering
.sortBy( t => (t._1(m_classIndex), t._3) )
// Assign each instance to fold
.zipWithIndex
.map( t => (t._1, t._2 % npartitions) )
val balancedRDDList =
for (f <- 0 until npartitions)
yield foldedRDD.filter( _._2 == f )
这篇关于如何使用相等的记录分割Spark数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文