python spark 通過key來統計不同values個數


>>> rdd = sc.parallelize([("a", "1"), ("b", 1), ("a", 1), ("a", 1)])
>>> rdd.distinct().countByKey().items()
[('a', 2), ('b', 1)]

OR:

from operator import add


rdd.distinct().map(lambda x: (x[0], 1)).reduceByKey(add)
rdd.distinct().keys().map(lambda x: (x, 1)).reduceByKey(add)

distinct(numPartitions=None)

Return a new RDD containing the distinct elements in this RDD.

>>> sorted(sc.parallelize([1, 1, 2, 3]).distinct().collect()) [1, 2, 3]

 countByKey()

Count the number of elements for each key, and return the result to the master as a dictionary.

>>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)]) >>> sorted(rdd.countByKey().items()) [('a', 2), ('b', 1)]



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM