2017-07-19 115 views
1

目前字符串數組的發生,我有兩個字段一個數據幀,名星火斯卡拉計數在圖例

id1,    id2 
Seq[String]  Map[String,(String,Long,Long)] 

我想創建一個名字率,這是另一列id1中id數量的百分比作爲地圖的關鍵字出現

看來我無法在udf中安裝for循環,想知道我應該怎麼做?

+0

你找每一標識百分比? –

回答

1

使用Seq.countMap.isDefinedAt檢查現有的地圖鍵的數量,然後簡單地用udf把它包:

val df = Seq((Seq("a", "b", "c"), Map("a" -> ("x", 1L, 2L), "x" -> ("y", 2L,2L)))).toDF("id1", "id2") 

type CustMap = Map[String, (String, Long, Long)] 

def percent_in = udf(
    (id1: Seq[String], id2: CustMap) => id1.count(id2.isDefinedAt)/id1.length.toDouble 
) 

df.withColumn("rate", percent_in($"id1", $"id2")).show 
+---------+--------------------+------------------+ 
|  id1|     id2|    rate| 
+---------+--------------------+------------------+ 
|[a, b, c]|Map(a -> [x,1,2],...|0.3333333333333333| 
+---------+--------------------+------------------+ 
+0

嗨,功能工作正常,但是,構建DF的方式給我一個錯誤顯示'表達式'ExternalMapToCatalyst_value_isNull19「不是一個右值',做了一些研究,但沒有那麼多人有這個問題 –