rebin an array in python to have at least N counts in each entry

61 Views Asked by At

I have an array as:

A = [1,8,2,6,4,8,1,0,1,6,7,3,1,4,9,1,2,1,2,1,1,2]

and I'd like to rebin/group it into a smaller size array, which has at least a value of 10 in each entry, i.e.:

A_reb = [[1,8,2],[6,4],[8,1,0,1],[6,7],[3,1,4,9],[1,2,1,2,1,1,2]]
A_reb = [11, 10, 10, 13, 17, 10]

Is there an effective way to do it in python? Thanks in advance.

2

There are 2 best solutions below

0
TheHungryCub On

Try this :

def rebin_array(arr):
    rebinned = []
    current_group = []
    current_sum = 0
    
    for num in arr:
        if current_sum + num <= 10:
            current_group.append(num)
            current_sum += num
        else:
            rebinned.append(current_group)
            current_group = [num]
            current_sum = num
    
    if current_group:
        rebinned.append(current_group)
    
    return rebinned

A = [1,8,2,6,4,8,1,0,1,6,7,3,1,4,9,1,2,1,2,1,1,2]
A_rebinned = rebin_array(A)
A_rebinned_sum = [sum(group) for group in A_rebinned]

print("A_rebinned:", A_rebinned)
print("A_rebinned_sum:", A_rebinned_sum)
0
mozway On

You can loop over the items, add the value to current total. If the total passes the threshold, append to the output and reset the total. Optionally add the last (incomplete) group to the output:

A = [1,8,2,6,4,8,1,0,1,6,7,3,1,4,9,1,2,1,2,1,1,2]

threshold = 10

start = 0
total = 0
out = []
for end, val in enumerate(A, start=1):
    total += val
    if total >= threshold:
        out.append(A[start:end])
        total = 0
        start = end

# if you want to add the last incomplete group (if any)
if start < len(A):
    out.append(A[start:])

Output:

[[1, 8, 2], [6, 4], [8, 1, 0, 1], [6, 7], [3, 1, 4, 9], [1, 2, 1, 2, 1, 1, 2]]