Generate a matrix of the sum of column values and sum of rows in new column in pyspark dataframe
colors = spark.createDataFrame([("Red","Re",20),("Blue","Bl",30),("Green","Gr",50)]).toDF("Colors","Prefix","Value") +------+------+-----+ |Colors|Prefix|Value| +------+------+-----+ | Red| Re| 20| | Blue| Bl| 30| | Green| Gr| 50| +------+------+-----+ piv = colors.groupby("Colors").pivot("Prefix").sum("Value").fillna(0) piv.withColumn("total",sum(piv[col] for col in piv.columns[1:])).show() +------+---+---+---+-----+ |Colors| Bl| Gr| Re|total| +------+---+---+---+-----+ | Green| 0| 50| 0| 50| | Blue| 30| 0| 0| 30| | Red| 0| 0| 20| 20| +------+---+---+---+-----+ Expecting even sum of columns like below (Expected dynamic code like if it has more columns and rows)
Re Bl Gr TOTAL Red 20 0 0 20 Blue 0 30 0 30 Green 0 0 50 50 TOTAL 20 30 50 100