How can I sum every n array values and place the r

2020-03-31 05:07发布

I have a very long list of array numbers I would like to sum and place into a new array. For example the array:

[1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8]

would become:

[6,15,16,6,15,x]

if I was to sum every 3.

I cannot figure out how to go about it. I think possibly one problem is I do not know the length of my array - I do not mind losing the bottom bit of data if necessary.

I have tried the numpy.reshape function with no success:

x_ave = numpy.mean(x.reshape(-1,5), axis=1)

ret = umr_sum(arr, axis, dtype, out, keepdims)

I get an error:

TypeError: cannot perform reduce with flexible type

3条回答
小情绪 Triste *
2楼-- · 2020-03-31 05:42

You can use a list comprehension do this:

ls = [1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8]
res = [sum(ls[i:i+3]) for i in range(0, len(ls), 3)]
[6, 15, 16, 9, 18, 8]

This will result in all the numbers being included in the resulting sum. If you don't want this to happen, then you can just check for it and replace the last sum with whatever value you want:

if (len(ls)%3) != 0:
    res[-1] = 'x' 
[6, 15, 16, 9, 18, 'x']

Or remove it entirely:

if (len(ls)%3) != 0:
    res[:] = res[:-1] 
[6, 15, 16, 9, 18]
查看更多
别忘想泡老子
3楼-- · 2020-03-31 05:43

Cut the array to the correct length first then do a reshape.

import numpy as np

N = 3
a = np.array([1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8])


# first cut it so that lenght of a % N is zero
rest = a.shape[0]%N
a = a[:-rest]


assert a.shape[0]%N == 0


# do the reshape
a_RS = a.reshape(-1,N)
print(a_RS)
>> [[1 2 3]
    [4 5 6]
    [7 8 1]
    [2 3 4]
    [5 6 7]]

then you can simply add it up:

print(np.sum(a_RS,axis=1))
>> [ 6 15 16  9 18]
查看更多
倾城 Initia
4楼-- · 2020-03-31 06:02

Why don't you just simply use a list comprehension? E.g.

my_list = [1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8]
len_list = len(my_list) - len(my_list) % 3  # ignore end of list, s.t., only tuples of three are considered
[my_list[i] + my_list[i+1] + my_list[i+2] for i in range(0, len_list, 3)]
查看更多
登录 后发表回答