Implement a PySpark function to calculate the average sales per category
Instruction: Write a PySpark code snippet to calculate the average sales per category using a given DataFrame containing 'category' and 'sales' columns. Ensure your solution handles any potential data issues.
Updated
State the input contract and rejected-row policy before computing an average. This example requires category as StringType and sales as DoubleType. It trims category names, accepts finite sales including refunds, and returns invalid rows separately instead of silently discarding them.
With an existing session named spark:
from pyspark.sql import functions as F
from pyspark.sql.types import StringType, DoubleType
def average_sales(df):
if len(df.columns) != len(set(df.columns)):
raise ValueError('Duplicate column names are not supported')
types = {field.name: field.dataType for field in df.schema.fields}
if types.get('category') != StringType() or types.get('sales') != DoubleType():
raise TypeError('Expected category:string and sales:double')
normalized = df.withColumn('category', F.trim('category'))
valid = (
F.col('category').isNotNull() & (F.length('category') > 0)
& F.col('sales').isNotNull() & ~F.isnan('sales')
& (F.abs(F.col('sales')) != F.lit(float('inf')))
)
valid = F.coalesce(valid, F.lit(False))
result = normalized.filter(valid).groupBy('category').agg(
F.avg('sales').alias('average_sales'), F.count('*').alias('accepted_rows')
)
rejected = normalized.filter(~valid)
return result, rejected
data = spark.createDataFrame(
[(' A ', 10.0), ('A', -2.0), ('B', 6.0), ('B', None),
(' ', 4.0), (None, 5.0), ('A', float('nan')), ('A', float('inf'))],
'category string, sales double'
)
result, rejected = average_sales(data)
assert [(r.category, r.average_sales, r.accepted_rows)
for r in result.orderBy('category').collect()] == [('A', 4.0, 2), ('B', 6.0, 1)]
assert rejected.count() == 5
This is an observed-row arithmetic mean, not revenue per customer or a weighted mean. Categories with no valid sales are absent; join an authoritative category list if they must appear with null averages and zero counts. Empty input produces an empty result. Keep original raw records separately if trimming or quarantine must be audited.
For currency, prefer a specified DecimalType, scale and overflow policy instead of binary floating point; adapt and test that contract explicitly. Finite inputs alone do not guarantee that every extreme floating-point aggregate is numerically safe. Do not silently cast arbitrary text or treat failed parsing as zero.