0

Before this question gets flagged and closed, I saw this question already, yet it does not quite answer my problem.

I would like to calculate the element-wise average over the arrays in the field per row, and keep the dimensionsionality

create table if not exists my_arrays (array_field float[]);

insert into my_arrays values ('{1,2,3}');
insert into my_arrays values ('{3,2,1}');
insert into my_arrays values ('{3,2,1}');
insert into my_arrays values ('{1,2,3}');

select avg(array_field) as x from my_arrays;

Which should output:

    x
---------
{2, 2, 2}

Is this possible?

1
  • The error is get is that no avg(float[]) exists ... Commented Nov 27, 2021 at 17:44

1 Answer 1

1

You can use unnest...with ordinality to break them apart while labeling their positions, then group by position, then reassemble with array_agg.

select array_agg(avg order by ordinality) from (
    select ordinality, avg(unnest) from my_arrays, unnest(array_field) with ordinality group by ordinality
) foo;

You need to make sure it deals with NULLs and missing values in a way you find suitable.

If you will be doing this a lot, it might make sense to define your own aggregate that operates over float[].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.