Home > Enterprise >  Numpy: reshape list of tuples
Numpy: reshape list of tuples

Time:03-25

I have the following list of tuples:

>>> import itertools
>>> import numpy as np
>>> grid = list(itertools.product((1,2,3),repeat=2))
>>> grid
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

I'd like to reshape this list in a sensible way (e.g. using numpy if possible) to be 3x3 as follows:

[[(1, 1), (1, 2), (1, 3)],
 [(2, 1), (2, 2), (2, 3)],
 [(3, 1), (3, 2), (3, 3)]]

When I do np.reshape(grid, (3, 3)) I get the following error: ValueError: cannot reshape array of size 18 into shape (3,3) (size 18??)

I've tried variations of np.reshape(grid, (3, 3, 2)) but these don't return the 3x3 grid given above.

CodePudding user response:

This will do the job:

new_grid = np.empty(len(grid), dtype='object')
new_grid[:] = grid
new_grid = new_grid.reshape(3, 3)

This outputs:

array([[(1, 1), (1, 2), (1, 3)],
       [(2, 1), (2, 2), (2, 3)],
       [(3, 1), (3, 2), (3, 3)]], dtype=object)

The object type will remain tuple:

type(new_grid[0, 0])
tuple

CodePudding user response:

18 comes from the fact that you have a list of 9 tuples, each containing 2 items; thus, 9 * 2 = 18. numpy automatically converts the tuples to part of the array.

You can either use LeonardoVaz's answer or do it speedily with nested list comprehension:

reshaped_grid = [[grid[i j] for j in range(3)] for i in range(len(grid) // 3)]

Output:

>>> reshaped_grid
[
    [(1, 1), (1, 2), (1, 3)],
    [(1, 2), (1, 3), (2, 1)],
    [(1, 3), (2, 1), (2, 2)]
]
  • Related