Python Pyspark计算分组表上的字段

Python Pyspark计算分组表上的字段,python,pyspark,apache-spark-sql,Python,Pyspark,Apache Spark Sql,我有一个数据框,看起来像这样: +-------+-----+-------------+------------+ |startID|endID|trip_distance|total_amount| +-------+-----+-------------+------------+ | 1| 3| 5| 12| | 1| 3| 0| 4| +-------+-----+----

我有一个数据框,看起来像这样:

+-------+-----+-------------+------------+
|startID|endID|trip_distance|total_amount|
+-------+-----+-------------+------------+
|      1|    3|            5|          12|
|      1|    3|            0|           4|
+-------+-----+-------------+------------+
+-------+-----+-----+----------+
|startID|endID|count| trip_rate|
+-------+-----+-----+----------+
|      1|    3|    2|       3.2|
+-------+-----+-----+----------+
我需要创建一个新表,根据起始ID和结束ID对行程进行分组,然后计算出平均行程率

行程率是通过使用相同起始ID和结束ID的所有行程计算得出的,在我的案例中,
startID
1和
endID
3总共有2次行程,对于这2次行程,平均
行程距离为2.5,平均
总金额为8。因此,跳闸率应为8/2.5=3.2

所以最终结果应该是这样的:

+-------+-----+-------------+------------+
|startID|endID|trip_distance|total_amount|
+-------+-----+-------------+------------+
|      1|    3|            5|          12|
|      1|    3|            0|           4|
+-------+-----+-------------+------------+
+-------+-----+-----+----------+
|startID|endID|count| trip_rate|
+-------+-----+-----+----------+
|      1|    3|    2|       3.2|
+-------+-----+-----+----------+
以下是我想做的:

from pyspark.shell import spark
from pyspark.sql.functions import avg

df = spark.createDataFrame(
    [
        (1, 3, 5, 12),
        (1, 3, 0, 4)
    ],
    ['startID', 'endID', 'trip_distance', 'total_amount'] # add your columns label here
)
df.show()
grouped_table = df.groupBy('startID', 'endID').count().alias('count')
grouped_table.show()

grouped_table = df.withColumn('trip_rate', (avg('total_amount') / avg('trip_distance')))
grouped_table.show()
但我得到了以下错误:

pyspark.sql.utils.AnalysisException: "grouping expressions sequence is empty, and '`startID`' is not an aggregate function. Wrap '((avg(`total_amount`) / avg(`trip_distance`)) AS `trip_rate`)' in windowing function(s) or wrap '`startID`' in first() (or first_value) if you don't care which value you get.;;\nAggregate [startID#0L, endID#1L, trip_distance#2L, total_amount#3L, (avg(total_amount#3L) / avg(trip_distance#2L)) AS trip_rate#44]\n+- LogicalRDD [startID#0L, endID#1L, trip_distance#2L, total_amount#3L], false\n"

我尝试将计算包装在AS函数中,但始终出现语法错误。

分组方式、求和和和除法
count
sum
可以在
agg()中使用


为什么你要用8除以3?它不应该是
8/2.5=3.2
?或者你是在舍入2.5你是对的,应该是3.2。我更新了这个问题,以防别人无意中发现。就是这样。非常感谢你!!