我试图随机采样列值满足特定条件的Pyspark数据框。我想使用该sample
方法根据列值随机选择行。假设我有以下数据框:
+---+----+------+-------------+------+
| id|code| amt|flag_outliers|result|
+---+----+------+-------------+------+
| 1| a| 10.9| 0| 0.0|
| 2| b| 20.7| 0| 0.0|
| 3| c| 30.4| 0| 1.0|
| 4| d| 40.98| 0| 1.0|
| 5| e| 50.21| 0| 2.0|
| 6| f| 60.7| 0| 2.0|
| 7| g| 70.8| 0| 2.0|
| 8| h| 80.43| 0| 3.0|
| 9| i| 90.12| 0| 3.0|
| 10| j|100.65| 0| 3.0|
+---+----+------+-------------+------+
我只想对0, 1, 2, 3
基于该result
列的每个样本进行1(或任何特定数量)的抽样,因此我将得出以下结论:
+---+----+------+-------------+------+
| id|code| amt|flag_outliers|result|
+---+----+------+-------------+------+
| 1| a| 10.9| 0| 0.0|
| 3| c| 30.4| 0| 1.0|
| 5| e| 50.21| 0| 2.0|
| 8| h| 80.43| 0| 3.0|
+---+----+------+-------------+------+
是否有一种好的编程方式来实现这一目标,即对于某一列中给出的每个值都采用相同数量的行?任何帮助都非常感谢!
您可以使用sampleBy()
,它返回分层样本而无需根据每个层次上给出的分数进行替换。
>>> from pyspark.sql.functions import col
>>> dataset = sqlContext.range(0, 100).select((col("id") % 3).alias("result"))
>>> sampled = dataset.sampleBy("result", fractions={0: 0.1, 1: 0.2}, seed=0)
>>> sampled.groupBy("result").count().orderBy("key").show()
+------+-----+
|result|count|
+------+-----+
| 0| 5|
| 1| 9|
+------+-----+
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句