-2

I have a list of lists that is in the following form (akin to a square matrix):

a = [[1,2,3,4,5,6],
     [5,6,7,8,3,4],
     [9,8,4,6,2,1],
     [3,4,5,1,4,5],
     [4,3,7,8,1,4],
     [3,2,5,6,1,8]]

I would like to get a new list of lists with the average of 4 adjacent values that forms a square, i.e. new_list[0][0] would be the mean of [1+2+5+6], new_list[0][1] would be the mean of [3+4+7+8], new_list[0][2] would be the mean of [5+6+3+4], and so on.

How can I achieve this in a pythonic way?

Thank you very much for any advice!

EDITED:

Thank you for pointing out this answer has been answered before - I didn't formulate my question clear enough it seems. Anyway, adapted from answer to this question, I got the solution:

a = np.array(a)

a_new = np.zeros((3, 3))

for i in range(3):
  for j in range(3):
    a_new[i][j] = np.mean(a[i*2:2+i*2, j*2:2+j*2])

cirnelle
  • 59
  • 3
  • 8

2 Answers2

0

If I understand the '4 adjacent values correctly' (lower right), you can do this by

a = np.array(a)

# create a placeholder
placeholder = []
for id_r, row in enumerate(a[::2]):
    tmp = []
    for id_c, col in enumerate(row[::2]):
        tmp.append(np.mean(a[id_r: id_r + 2, id_c: id_c + 2]))
    placeholder.append(tmp)
meTchaikovsky
  • 7,478
  • 2
  • 15
  • 34
0

I would just use two for loops and accumulate the mean of each square:

from statistics import mean

a = [[1,2,3,4,5,6],
     [5,6,7,8,3,4],
     [9,8,4,6,2,1],
     [3,4,5,1,4,5],
     [4,3,7,8,1,4],
     [3,2,5,6,1,8]]

new_list = []
for i in range(len(a) - 1):
    row = []
    for j in range(len(a[i]) - 1):
        square = a[i][j], a[i][j+1], a[i+1][j], a[i+1][j+1]
        row.append(mean(square))
    new_list.append(row)

print(new_list)
# [[3.5, 4.5, 5.5, 5, 4.5], [7, 6.25, 6.25, 4.75, 2.5], [6, 5.25, 4, 3.25, 3], [3.5, 4.75, 5.25, 3.5, 3.5], [3, 4.25, 6.5, 4, 3.5]]

You could also use a less readable list comprehension:

[[mean((a[i][j], a[i][j+1], a[i+1][j], a[i+1][j+1])) for j in range(len(a[i]) - 1)] for i in range(len(a) - 1)]
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
  • Thank you! Similar to meTchaikovsky's answer below - this is not quite what I want yet, I don't want the squares to overlap, i.e. new_list[0][1] is the mean of 3+4+7+8, not 2+3+6+7 – cirnelle Oct 10 '19 at 06:39