NycoElm
NycoElm

Reputation: 5

Filling a 2D array using a 3D array in python

I'm having some trouble in Python as beginner. Let me use some example and let's consider the foloowing data :

data = [[1, 7],
        [2, 8],
        [3, 9],
        [4, 10],
        [5, 11],
        [6, 12],
        [13, 14],
        [15, 16]]

I want as output :

B       = [[1+3+5+13, 7+9+11+14],
          [2+4+6+15, 8+10+12+16]]

To do it, i already tried to slice the data array into smaller arrays (2x2), but i can't find a way to make it works. I think that if i can find a way to make this small program works, I will be able to work with bigger files of data.

So that's my actual code :

A= {}
m=2
A=[data[idx: idx + m] for idx in range(0, len(data), m)]
B=[]
for a in range(1,2) :
    for l in range(2):
        B.append([])
        for c in range(2):
            B[l].append(A[a][l][c])
            print('B = ' + str(B))
print('end')

Thank you for your time.

Upvotes: 0

Views: 108

Answers (3)

vachmara
vachmara

Reputation: 126

This code should also work :

X1 = [x[0] for x in data]
X2 = [x[1] for x in data]

B = [ [sum(X1[0::2]), sum(X2[0::2])], 
      [sum(X1[1::2]), sum(X2[1::2])]]

Upvotes: 0

T.L
T.L

Reputation: 26

def slice_array(raw_data):
    ret = [[0,0],
          [0,0]]
    for d in range(len(raw_data)):
        if d % 2 == 0:
           ret [0][0] += raw_data[d][0]
           ret [0][1] += raw_data[d][1] 
        if d % 2 == 1:
           ret [1][0] += raw_data[d][0]
           ret [1][1] += raw_data[d][1] 
    return ret

This should work. Just give the array you want to slice as input.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249113

The four sums you want can be calculated efficiently like this:

import numpy as np
arr = np.array(data)

w = arr[0::2,0] # array([ 1,  3,  5, 13])
x = arr[0::2,1] # array([ 7,  9, 11, 14])
y = arr[1::2,0] # array([ 2,  4,  6, 15])
z = arr[1::2,1] # array([ 8, 10, 12, 16])

B = [[w.sum(), x.sum()], [y.sum(), z.sum()]]

arr[1::2,0] means "Starting from row 1, take every second row, then take column 0."

Upvotes: 1

Related Questions