使用NumPy创建一个数组,它是给定大小的每个连续子数组的平均值
在这篇文章中,我们将看到创建一个元素数组的程序,其中每个元素都是给定的numpy数组中大小为k的每个连续子数组的平均值,这样k是n的一个因子,即(n%k=0)。这项任务可以通过使用numpy.mean()和numpy.reshape()函数一起完成。
语法: numpy.mean(arr, axis = None)
返回:数组的算术平均值(如果没有轴,则为标量值),或者数组中沿指定轴的平均值。
语法: numpy_array.reshape(shape)
返回:它返回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
以下是实施情况。
# 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]