K--
K--

Reputation: 734

Numpy: reshape list of tuples

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.

Upvotes: 0

Views: 429

Answers (2)

user17242583
user17242583

Reputation:

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(0, len(grid), 3)]

Output:

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

Upvotes: 1

LeonardoVaz
LeonardoVaz

Reputation: 311

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

Upvotes: 1

Related Questions