N Dimensional Arrays - Python / Numpy

just wondering if there is any smart 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]] 

To get the first line , I do the following:

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

To get the first column , I would like to do something like this (although this is not possible):

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

Does NumPy support something like this by accident?


Any ideas?

+4
source share
3 answers

Yes, there is something similar 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]) 
+10
source

You can use zip to transfer the matrix, presented as a list of lists:

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

Nothing more than simple, and I would use Numpy.

+2
source

To get columns in Python, you can use:

 [row[0] for row in grid] >>> [1,4,7] 

You can rewrite your code to get the string as

 grid[0][:] 

because [:] just copies the whole array, there is no need to add indexes.

However, depending on what you want to achieve, I would say that it’s better to just write a small matrix class to hide this implementation material.

+1
source

Source: https://habr.com/ru/post/1336764/


All Articles