pyspark.RDD.groupByKey

RDD. groupByKey ( numPartitions: Optional[int] = None, partitionFunc: Callable[[K], int] = <function portable_hash> ) → pyspark.rdd.RDD [ Tuple [ K , Iterable [ V ] ] ] [source]

将RDD中每个键的值分组为一个序列。 使用numPartitions分区对生成的RDD进行哈希分区。

新增于版本 0.7.0。

Parameters
numPartitions int, optional

RDD 中的分区数量

partitionFunc function, optional, default portable_hash

计算分区索引的函数

Returns
RDD

包含键和每个键的分组结果的 RDD

注释

如果你是为了对每个键执行聚合操作(例如求和或平均值)而进行分组,使用 reduceByKey 或 aggregateByKey 将会提供更好的性能。

示例

>>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)])
>>> sorted(rdd.groupByKey().mapValues(len).collect())
[('a', 2), ('b', 1)]
>>> sorted(rdd.groupByKey().mapValues(list).collect())
[('a', [1, 1]), ('b', [1])]