使用 NumPy 创建一个数组,该数组是给定大小的每个连续子数组的平均值
在本文中,我们将看到创建元素数组的程序,其中每个元素是给定大小为 n 的 numpy 数组的每个大小为 k 的连续子数组的平均值,使得 k 是 n 的因子,即 (n%k ==0)。这个任务可以通过一起使用 numpy.mean() 和 numpy.reshape() 函数来完成。
Syntax: numpy.mean(arr, axis = None)
Return: Arithmetic mean of the array (a scalar value if axis is none) or array with mean values along specified axis.
Syntax: numpy_array.reshape(shape)
Return: It returns numpy.ndarray
例子 :
Arr = [1,2,3,4,5,6
7,8,9,10,11
12,13,14,15,16]
and K = 2 then
Output is [ 1.5, 3.5, 5.5, 7.5,
9.5, 11.5, 13.5, 15.5].
Here, subarray of size k and there average are calculated as :
[1 2] avg = ( 1 + 2 ) / 2 = 1.5
[3 4] avg = ( 3 + 4 ) / 2 = 3.5
[5 6] avg = ( 5 + 6 ) / 2 = 5.5
[7 8] avg = ( 7 + 8 ) / 2 = 7.5
[9 10] avg = ( 9 + 10 ) / 2 = 9.5
[11 12] avg = ( 11 + 12 ) / 2 = 11.5
[13 14] avg = ( 13 + 14 ) / 2 = 13.5
[15 16] avg = ( 15 + 16 ) / 2 = 15.5
下面是实现:
Python3
# importing library
import numpy
# create numpy array
arr = numpy.array([1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14,
15, 16])
# view array
print("Given Array:\n", arr)
# declare k
k = 2
# find the mean
output = numpy.mean(arr.reshape(-1, k),
axis=1)
# view output
print("Output Array:\n", output)
输出:
Given Array:
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
Output Array:
[ 1.5 3.5 5.5 7.5 9.5 11.5 13.5 15.5]