bux
bux

Reputation: 7739

Convert one dimensional point list in two dimensional np array

I've one dimensional position list of 10x10 grid:

[(0, 0), (0, 1), (0, 2), ..., (9, 9)]

I would like numpy array like this (list of 10 length list):

array([[ (0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9) ],
       ...,
       [ (9, 0), (9, 1), (9, 2), (9, 3), (9, 4), (9, 5), (9, 6), (9, 7), (9, 8), (9, 9) ]])

How to convert one dimensional point list in two dimensional np array ?

I wrote this:

import numpy as np

l = []
for i in range(10):
    for ii in range(10):
        l.append((i, ii))

print(l)
a = np.array(l)
print(a)
a.shape = (a.size // 10, 10)
print(a)

But result is not what expected:

python3.4 tmp/t.py
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), ..., (9, 9)]
[[0 0]
 [0 1]
 [0 2]
 [0 3]
 [0 4]
 [0 5]
 [0 6]
 [0 7]
 [0 8]
 [0 9]
 ...
 [9 9]]
[[0 0 0 1 0 2 0 3 0 4]
 [0 5 0 6 0 7 0 8 0 9]
 [1 0 1 1 1 2 1 3 1 4]
 [1 5 1 6 1 7 1 8 1 9]
 [2 0 2 1 2 2 2 3 2 4]
 ...
 [9 0 9 1 9 2 9 3 9 4]
 [9 5 9 6 9 7 9 8 9 9]]

Upvotes: 1

Views: 295

Answers (2)

Alex Huszagh
Alex Huszagh

Reputation: 14614

You want numpy.reshape

>>> array = np.array(range(10))
>>> array.reshape(5,2)
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7],
       [8, 9]])

For your case, if you were dealing with a single element, you would do the following:

>>> >>> a = np.array(range(100))
>>> a.reshape(10,10)
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
       [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
       [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
       [70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
       [80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
       [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])

However, your case has 2 elements for each element, so you would do:

>>> a = np.array([[i,j] for i in range(10) for j in range(10)])
>>> a.reshape(10,10, 2)

Upvotes: 1

Irshad Bhat
Irshad Bhat

Reputation: 8709

Try this:

>>> z = [(i,j) for i in range(10) for j in range(10)]
>>> z
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), ..., (9, 9)]
>>> np.array(z).reshape((10,10, 2))
array([[[0, 0],
        [0, 1],
        [0, 2],
        [0, 3],
        [0, 4],
        [0, 5],
        [0, 6],
        [0, 7],
        [0, 8],
        [0, 9]],

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

        ...

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

Upvotes: 3

Related Questions