代码之家  ›  专栏  ›  技术社区  ›  strawberryBeef

使用sparkyr获取Spark数据帧的max索引

  •  1
  • strawberryBeef  · 技术社区  · 6 年前

    我试图从Spark数据帧中获取行中最大值的索引。直接得到最大值。我做了以下工作:

    library(sparklyr)
    library(dplyr)
    
    config <- spark_config()
    sc <- spark_connect(master = "local", config = config)
    
    df <- replicate(n = 3, sample(x = 0:10,size = 10, rep=TRUE)) %>%
      as.data.frame()
    
    
    sdf <- sdf_copy_to(sc, df, overwrite = T)
    
    sdf %>% spark_apply(
      function(df) {
        return( pmax(df[1], df[2], df[3]) )})
    

    我试着用 ft_vector_assembler 但我不熟悉返回的数据结构。例如,我无法从以下代码中恢复max

    sdf %>% ft_vector_assembler(
      input_cols = c("V1", "V2", "V3"), 
      output_col = "features") %>%
      select(features) %>%
      spark_apply( function(df) pmax(df))
    

    1 回复  |  直到 6 年前
        1
  •  1
  •   zero323 little_kid_pea    6 年前

    直接得到最大值。

    然而,事实确实如此 spark_apply 只是这不是一条路要走。相反,最好使用 greatest 功能:

    sdf %>% mutate(max = greatest(V1, V2, V3))
    

    同样的函数可以用于第二个问题,但是由于 sparklyr

    expr <- c("V1", "V2", "V3") %>% 
      paste0(
        "CAST(STRUCT(`",
        ., "`, ", seq_along(.),
        ") AS struct<value: double, index: double>)", collapse=", ")  %>% 
      paste0("greatest(", ., ").index AS max_index")
    
    sdf %>% 
      spark_dataframe() %>%
      invoke("selectExpr", list("*", expr)) %>%
      sdf_register()
    

    在Spark 2.4中(目前在 )它

    sdf %>% mutate(max
      max_index = array_max(arrays_zip(array(V1, V2, V3), array(1, 2, 3))).1
    )