First install Numpy into your Python environment and load it
For that
Either do
sudo apt-get install python-numpy
or
Numpy can be imported in Python interface by typing the command from numpy import *. Once you import the package in to the Python environment, it is ready to use. Ready, Steady, Go!!!
>>>from numpy import * >>>import numpy as np >>>A= np.array ([[78, 41, 53], [65, 86, 49], [94, 49, 56]])
Like most modern programming languages, indexing starts from 0. The element 78 is referred to as A[0,0]. Type the following:
>>>A[0] # first row >>>A[-1] # last row >>>A[0,0] # first row, first column >>>A[0,1] # first row, second column >>>A[:2] # first two rows >>>A[:,1] # second column
To create an array with elements in the range 0–99, the following code can be used.
>>>import numpy as np >>>x =np.array(range(100))
Here is another Python magic, if you would like to convert the array created just now into three 4x2 matrices, you can simply use the following command:
>>>x.reshape((4,5,5)) >>>x.reshape((5,4,5))
To define matrices consisting only of zeroes or ones, or an identity matrix, try the following:
>>>np.zeros((2,4)) >>>np.ones((2,4)) >>>np.identity(3)
If you wish to create a matrix with a dimension same as that of another matrix, but containing elements as only zeroes, or only ones, it is very easy in Python! Try the following:
>>>np.ones_like(A) >>>np.zeros_like(A)
To split an array with elements 0 to 19 into three, try the following command:
>>>x =array(range(20)) >>>split=array_split(x, 3)
To create a list dynamically
list2d=[[] for i in xrange(8)]
list2d[0]=[1,2,3,4,5,6,7,8,9,10,11]
list2d[1]=[12,13,14,15,16,17,18,19]
Create a matrix
n = 3
m = 3
val = [0] * n
for x in range (n):
val[x] = [0] * m
print(val)
Another way to do this
# Create an 4 x 5 matrix of 1's:
w, h = 4, 5;
MyMatrix = [ [1 for x in range( w )] for y in range( h ) ]
print MyMatrix
Creating array is fun
# Create an 4 x 5 matrix of 1's:
a,b,n=1,1,6
MyMatrix = MyFunkyArray = [ x*a + b for x in range ( n ) ]
print MyMatrix
Add rows or columns using vstack
import numpy as np
ini_array = np.array([[1, 2, 3], [45, 4, 7], [9, 6, 10]])
# printing initial array
print("initial_array : ", str(ini_array));
# Array to be added as row
rowadded = np.array([1, 2, 3])
# Adding row to numpy array
result = np.vstack ((ini_array, rowadded) )
# printing result
print ("resultant array", str(result))
import numpy as np
ini_array = np.array([[1, 2, 3], [45, 4, 7], [9, 6, 10]])
# printing initial array
print("initial_array : ", str(ini_array));
# Array to be added as column
coladded = np.array([1, 2, 3])
# Adding column to numpy array
result = np.hstack((ini_array, np.atleast_2d(coladded).T))
# printing result
print ("resultant array", str(result))