Python NumPy Multi-dimensional Arrays
>>> from numpy import *
>>> arr = arange(1, 25, 2)
>>> arr
array([ 1,  3,  5,  7,  9, 11, 13, 15, 17, 19, 21, 23])

>>> arr.reshape(3, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot reshape array of size 12 into shape (3,3)

>>> arr.reshape(3, 4)
array([[ 1,  3,  5,  7],
       [ 9, 11, 13, 15],
       [17, 19, 21, 23]])

>>> reshape(arr, (4, 3))
array([[ 1,  3,  5],
       [ 7,  9, 11],
       [13, 15, 17],
       [19, 21, 23]])
       
>>> arr = arr.reshape(4, 3)
>>> arr
array([[ 1,  3,  5],
       [ 7,  9, 11],
       [13, 15, 17],
       [19, 21, 23]])

>>> arr[1]
array([ 7,  9, 11])

>>> arr[1, 1]
9

>>> arr.ndim
2

>>> shape(arr)
(4, 3)

>>> shape(arr)[0]
4

>>> shape(arr)[1]
3

>>> arr array([[ 1, 3, 5], [ 7, 9, 11], [13, 15, 17], [19, 21, 23]]) >>> arr[0,:] array([1, 3, 5]) >>> arr[:,0] array([ 1, 7, 13, 19]) >>> arr[0:3] array([[ 1, 3, 5], [ 7, 9, 11], [13, 15, 17]]) >>> arr[1:4] array([[ 7, 9, 11], [13, 15, 17], [19, 21, 23]]) >>> arr[::-1] array([[19, 21, 23], [13, 15, 17], [ 7, 9, 11], [ 1, 3, 5]]) >>> arr = arr.flatten() >>> arr array([ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]) >>> arr.ndim 1
>>> zeros((4, 3), int) array([[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]) >>> ones((4, 3), int) array([[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]) >>> eye(3) array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
Advertisement