Ask Your Question
2

What is the average of each pair of consecutive elements in a numpy array?

asked 2023-06-09 05:34:06 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-09 05:59:02 +0000

djk gravatar image

You can use numpy's built-in function numpy.mean(array, axis) to calculate the average of each pair of consecutive elements in a numpy array:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])
arr_average = np.mean(arr.reshape(-1, 2), axis=1)
print(arr_average)

This will output:

[1.5 3.5 5.5]

Here, we first reshape the array into sub-arrays of length 2 using arr.reshape(-1, 2). Then we calculate the mean along the first axis (axis=1), which corresponds to the mean of each pair of consecutive elements.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-09 05:34:06 +0000

Seen: 20 times

Last updated: Jun 09 '23