2017-08-10 37 views
0

如何在数据框上应用条件,例如我需要对一列进行groupBy并根据某些条件来计算列中的不同值。这在多列的条件如何在数据框上进行聚合以获得不同数量的列

我试了下面的方式。请让我知道我该怎么做。

case class testRdd(name:String,id:Int,price:Int) 
val Cols = testRdd.toDF().groupBy("id").agg(countDistinct("name").when(col("price")>0,1).otherwise(0) 

这将无法正常工作,或者是否有办法做类似的事情?在此先感谢

testRdd.toDF().groupBy("id").agg(if(col("price")>0)countDistinct("name")) 

回答

0

testRDD.select( “名”, “ID”)。其中($ “价格”> 0).distinct.groupBy($ “ID”)。AGG(计数( “名” ))。显示

0

这是一种替代方法,以@罗宾的答案,即引入额外的布尔列组

df.groupBy($"id",when($"price">0,true).otherwise(false).as("positive_price")) 
.agg(
    countDistinct($"name") 
) 
.where($"positive_price") 
.show 
+0

我有多个列应用WHERE条件上,1列,我可以做到这一点,但我无法在其中添加更多列,有没有办法在多列上应用 – Babu

相关问题