numpy \m/ python

Python is simple,elegant,consistent and math-like.One of my earlier articles was on pandas in python. In this one we shall look into basics of  'numpy' library in python.
NumPy is the fundamental package for scientific computing with Python. It contains among other things:
  • a powerful N-dimensional array object
  • sophisticated (broadcasting) functions
  • tools for integrating C/C++ and Fortran code
  • useful linear algebra, Fourier transform, and random number capabilities 
 Why numpy and not list, because numpy:
  > is fast
  > takes less space
  > is convenient
Following examples will illustrate these 3 benefits
a) numpy is way faster
import numpy as np
import time

SIZE=1000000
L1=range(SIZE)
L2=range(SIZE)

NP1=np.arange(SIZE)
NP2=np.arange(SIZE)

start=time.time()
list_result=[x + y for x, y in zip(L1, L2)]
print((time.time()-start)*1000)

start1=time.time()
n_result=NP1+NP2
print((time.time()-start1)*1000)
 Output:
356.6305637359619
2.0096302032470703
b) numpy takes less space:
import numpy as np
import sys

my_list=range(1000)
print(sys.getsizeof(5)*len(my_list))

var_numpy=np.arange(1000)
print(var_numpy.size*var_numpy.itemsize)
Output:
28000
4000

numpy Operations
import numpy as np

var=np.array([(1,3,5),(2,4,6)])

print(var)
print(type(var)) # what type var variable isprint(var.ndim)  # dimensions of the numpy arrayprint(var.itemsize) #bytesize of each elementprint(var.dtype)  # data type of the elementsprint((var.size)) #number of elementsprint(var.shape) # gives (r,c) r is number of rows and c is number of columnsprint(var.reshape(3,2))

var2=np.linspace(1,3,5) #Return evenly spaced numbers over a specified interval.print(var2)
print(var.max())
print(var.min())
print(var.mean())
print(var.sum())
print(var.sum(axis=0)) #print sum of indidual columnsprint(var.sum(axis=1))  # print sum of individual rows
print(np.sqrt(var))
print(np.std(var))# standard deviation
x=np.array([1,2,3])
y=np.array([4,5,6])
print(x+y)  # addition of 2 arrays
print(var.ravel())
Output:
[[1 3 5]
 [2 4 6]]
<class 'numpy.ndarray'>
2
4
int32
6
(2, 3)
[[1 3]
 [5 2]
 [4 6]]
[ 1.   1.5  2.   2.5  3. ]
6
1
3.5
21
[ 3  7 11]
[ 9 12]
[[ 1.          1.73205081  2.23606798]
 [ 1.41421356  2.          2.44948974]]
1.70782512766
[5 7 9]
[1 3 5 2 4 6]


Comments

Popular Posts