You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Numpy一维数组元素级均值计算:是否存在内置实现方法?

Answer to Element-Wise Consecutive Mean in NumPy

Great question! You don’t need to roll your own custom function for this—NumPy has several built-in ways to compute the mean of consecutive element pairs (or any sliding window mean, if you ever need a larger window). Here are the most practical approaches:

1. Simple Slicing (Best for Pairwise Mean)

This is the most efficient and readable method for your exact use case. It leverages basic array slicing to pair each element with its neighbor, then computes the average:

import numpy as np
a = np.array([1, 3, 5, 7])
b = (a[:-1] + a[1:]) / 2
print(b)  # Output: array([2., 4., 6.])
  • a[:-1] takes all elements except the last one: [1,3,5]
  • a[1:] takes all elements except the first one: [3,5,7]
  • Adding these two arrays element-wise and dividing by 2 gives the pairwise mean directly.

2. Sliding Window View (Generalizable to Larger Windows)

If you ever need to compute the mean over a larger sliding window (e.g., 3 consecutive elements), use numpy.lib.stride_tricks.sliding_window_view (available in NumPy 1.20.0+). It creates a view of your array with sliding windows, then you can take the mean along the window axis:

from numpy.lib.stride_tricks import sliding_window_view
a = np.array([1, 3, 5, 7])
windowed_array = sliding_window_view(a, window_shape=2)
b = windowed_array.mean(axis=1)
print(b)  # Output: array([2., 4., 6.])

This approach scales easily—just change window_shape to 3 if you want the mean of every 3 consecutive elements, and it’ll work without modifying the rest of your code.

3. Convolution (Alternative for Signal Processing Contexts)

Another option is using numpy.convolve with a kernel that averages adjacent elements. While it’s less intuitive for this specific task, it’s useful if you’re working in a signal processing context:

import numpy as np
a = np.array([1, 3, 5, 7])
b = np.convolve(a, [0.5, 0.5], mode='valid')
print(b)  # Output: array([2., 4., 6.])

The kernel [0.5, 0.5] weights each element equally, and mode='valid' ensures we only get results where the kernel fits fully over the input array (avoiding edge padding).

Recommendation

For your exact use case (pairwise consecutive mean), stick with the slicing method—it’s the fastest and easiest to understand. The sliding window view is the way to go if you need flexibility for larger windows later on.

内容的提问来源于stack exchange,提问作者mitchute

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:53:35