Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

N dimensional arrays - Python/Numpy

just wondering if there is any clever way to do the following.

I have an N dimensional array representing a 3x3 grid

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

In order to get the first row I do the following:

grid[0][0:3]
>> [1,2,3]

In order to get the first column I would like to do something like this (even though it is not possible):

grid[0:3][0]
>> [1,4,7]

Does NumPy support anything similar to this by chance?


Any ideas?

like image 584
RadiantHex Avatar asked Dec 12 '22 16:12

RadiantHex


2 Answers

Yes, there is something like that in Numpy:

import numpy as np

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

grid[0,:]
# array([1, 2, 3])

grid[:,0]
# array([1, 4, 7])
like image 158
eumiro Avatar answered Dec 15 '22 05:12

eumiro


You can use zip to transpose a matrix represented as a list of lists:

>>> zip(*grid)[0]
(1, 4, 7)

Anything more than just that, and I'd use Numpy.

like image 44
Michael J. Barber Avatar answered Dec 15 '22 06:12

Michael J. Barber