I am trying to average each element of a column of arrays by index on a group by, so that I can start with a dataframe like this:
-----------------------
id | weights
-----------------------
1 | [ 34, 23, 56 ]
1 | [ 5, 45, 10 ]
1 | [ 38, 30, 50 ]
2 | [ 45, 5, 20 ]
2 | [ 40, 11, 23 ]
Then groupby "id" and somehow have an array with an average of the weights per index:
-----------------------
id | weights
-----------------------
1 | [ 25.667, 32.667, 38.667 ]
2 | [ 42.5, 8, 21.5 ]
I know that I could do this by splitting "weights" into separate columns and then doing groupby. The only issue is that the above is just an example, and the array in my real weights column has 300 elements. I've been able to see that I can get a few elements split up with this code:
sample_output.select($"weights".getItem(0).as("First"),
$"weights".getItem(1).as("Second"),
$"weights".getItem(2).as("Third"))
.show()
However, I don't want to have to write that out for 300 elements. I next tried creating a list of strings for all of my columns and selecting that from my df:
val dimNums = (0 until typedConfig.embeddingDims).toList
val all_columns = dimNums.map(x => "$\"weights\".getItem(%d).as(\"dim%d\")".format(x,x))
sample_output.select(all_columns.head, all_columns.tail: _*)
.show(false)
This gave me the error:
org.apache.spark.sql.AnalysisException: cannot resolve '
$"weights".getItem(0).as("dim0")' given input columns: [id, WordToken, weights];;
I also tried:
sample_output.select(all_columns.map(col): _*).show(false)
But I got the exact same error. Does anyone know a way to split up a huge array like this into several columns? Or else is there another way that I can average these lists by index while using groupby?