Making histogram with Spark DataFrame column

前端 未结 6 1956
盖世英雄少女心
盖世英雄少女心 2020-12-16 03:18

I am trying to make a histogram with a column from a dataframe which looks like

DataFrame[C0: int, C1: int, ...]

If I were to make a histog

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-16 03:25

    You can use histogram_numeric Hive UDAF:

    import random
    
    random.seed(323)
    
    sqlContext = HiveContext(sc)
    n = 3  # Number of buckets
    df = sqlContext.createDataFrame(
        sc.parallelize(enumerate(random.random() for _ in range(1000))),
       ["id", "v"]
    )
    
    hists = df.selectExpr("histogram_numeric({0}, {1})".format("v", n))
    
    hists.show(1, False)
    ## +------------------------------------------------------------------------------------+
    ## |histogram_numeric(v,3)                                                              |
    ## +------------------------------------------------------------------------------------+
    ## |[[0.2124888140177466,415.0], [0.5918851340384337,330.0], [0.8890271451209697,255.0]]|
    ## +------------------------------------------------------------------------------------+
    

    You can also extract the column of interest and use histogram method on RDD:

    df.select("v").rdd.flatMap(lambda x: x).histogram(n)
    ## ([0.002028109534323752,
    ##  0.33410233677189705,
    ##  0.6661765640094703,
    ##  0.9982507912470436],
    ## [327, 326, 347])
    

提交回复
热议问题