I have a PySpark dataframe-
df = spark.createDataFrame([
("u1", [[1., 2., 3.], [1., 2., 0.], [1., 0., 0.]]),
("u2", [[1., 10., 0.]]),
("u3", [[1., 0., 3.], [10., 0., 0.]]),
],
['user_id', 'features'])
print(df.printSchema())
df.show(truncate=False)
Output-
root
|-- user_id: string (nullable = true)
|-- features: array (nullable = true)
| |-- element: array (containsNull = true)
| | |-- element: double (containsNull = true)
None
+-------+---------------------------------------------------+
|user_id|features |
+-------+---------------------------------------------------+
|u1 |[[1.0, 2.0, 3.0], [1.0, 2.0, 0.0], [1.0, 0.0, 0.0]]|
|u2 |[[1.0, 10.0, 0.0]] |
|u3 |[[1.0, 0.0, 3.0], [10.0, 0.0, 0.0]] |
+-------+---------------------------------------------------+
I want to calculate the average of these arrays for every user on the 0th axis. The desired output would look like-
+-------+---------------------------------------------------+----------------+
|user_id|features |avg_features |
+-------+---------------------------------------------------+----------------+
|u1 |[[1.0, 2.0, 3.0], [1.0, 2.0, 0.0], [1.0, 0.0, 0.0]]|[1.0, 1.33, 1.0]|
|u2 |[[1.0, 10.0, 0.0]] |[1.0, 10.0, 0.0]|
|u3 |[[1.0, 0.0, 3.0], [10.0, 0.0, 0.0]] |[5.5, 0.0, 1.5]|
+-------+---------------------------------------------------+----------------+
How do I achieve this?