Pyspark pypark中的Dataframe-如何将聚合函数应用到两列中?

Pyspark pypark中的Dataframe-如何将聚合函数应用到两列中?,pyspark,hivecontext,Pyspark,Hivecontext,我在pyspark中使用数据帧。我有一张像贝娄一号桌的桌子。我需要得到表2。其中: num_category-它是每个id有多少个不同的类别 总和(计数)-它是表1中每个id的第三列的总和 例如: 表1 id |category | count 1 | 4 | 1 1 | 3 | 2 1 | 1 | 2 2 | 2 | 1 2 | 1 | 1 表2 id |num_c

我在pyspark中使用数据帧。我有一张像贝娄一号桌的桌子。我需要得到表2。其中:

  • num_category-它是每个id有多少个不同的类别
  • 总和(计数)-它是表1中每个id的第三列的总和
例如:

表1

id   |category | count 

1    |    4    |   1 
1    |    3    |   2
1    |    1    |   2
2    |    2    |   1
2    |    1    |   1
表2

id   |num_category| sum(count) 

1    |    3       |   5 
2    |    2       |   2
我尝试:

table1 = data.groupBy("id","category").agg(count("*"))
cat = table1.groupBy("id").agg(count("*"))
count = table1.groupBy("id").agg(func.sum("count"))
table2 = cat.join(count, cat.id == count.id)
错误:


您可以对单个分组数据进行多列聚合

data.groupby('id').agg({'category':'count','count':'sum'}).withColumnRenamed('count(category)',"num_category").show()
+---+-------+--------+
| id|num_cat|sum(cnt)|
+---+-------+--------+
|  1|      3|       5|
|  2|      2|       2|
+---+-------+--------+

您可以对单个分组数据进行多列聚合

data.groupby('id').agg({'category':'count','count':'sum'}).withColumnRenamed('count(category)',"num_category").show()
+---+-------+--------+
| id|num_cat|sum(cnt)|
+---+-------+--------+
|  1|      3|       5|
|  2|      2|       2|
+---+-------+--------+