Bor*_*ris 3 random apache-spark apache-spark-sql
如何有效地从 DataFrame 中选择精确数量的随机行?数据包含可以使用的索引列。如果我必须在索引列上使用最大大小,count() 或 max() 哪个更有效?
一种可能的方法是使用 计算行数.count()
,然后使用sample()
frompython
的随机库从此范围生成任意长度的随机序列。最后使用生成的数字列表vals
来子集索引列。
import random
def sampler(df, col, records):
# Calculate number of rows
colmax = df.count()
# Create random sample from range
vals = random.sample(range(1, colmax), records)
# Use 'vals' to filter DataFrame using 'isin'
return df.filter(df[col].isin(vals))
Run Code Online (Sandbox Code Playgroud)
例子:
df = sc.parallelize([(1,1),(2,1),
(3,1),(4,0),
(5,0),(6,1),
(7,1),(8,0),
(9,0),(10,1)]).toDF(["a","b"])
sampler(df,"a",3).show()
+---+---+
| a| b|
+---+---+
| 3| 1|
| 4| 0|
| 6| 1|
+---+---+
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10139 次 |
最近记录: |