Numpy Matplot
Numpy Matplot
Python Libraries
Numpy(Numerical Python), Matplotlib
There are several ways to import NumPy. The standard approach is to use a simple
import statement:
12
Array Creation
There are several ways to create arrays.
For example, you can create an array from a regular Python list or tuple using
the array function. The type of the resulting array is deduced from the type of the
elements in the sequences.
import numpy as np a.dtype
a = np.array([2,3,4]) dtype('int64')
a b = np.array([1.2, 3.5, 5.1])
array([2, 3, 4])
b.dtype
print(a)
[2 3 4] dtype ('float64')
A frequent error consists in calling array with multiple numeric arguments, rat
her than providing a single list of numbers as an argument.
a = np.array(1,2,3,4) # WRONG
a = np.array([1,2,3,4]) # RIGHT
np.empty( (2,2) ) # the function empty creates an array whose initial conte
nt is
# random & depends on the state of the memor
y
array([[4.16254416e+196, 6.58798947e-293],
[6.68007707e-294, 1.99178933e-306]])
numpy.asarray()
Printing Arrays
When you print an array, NumPy displays it in a similar way to nested lists, but with
the following layout:
the last axis is printed from left to right,
the 2nd-to-last is printed from top to bottom,
the rest are also printed from top to bottom, with each slice separated from the
next by an empty line.
1-dimensional arrays are printed as rows,
bi-dimensional as matrices &
tri-dimensional as lists of matrices.
a = np.arange(6) # 1d array c = np.arange(24).reshape(2,3,4) # 3d array
print(a) print(c)
[0 1 2 3 4 5] [ [ [ 0 1 2 3]
b = np.arange(12).reshape(4,3) # 2d array [ 4 5 6 7]
print(b) [ 8 9 10 11] ]
[[ 0 1 2]
[ 3 4 5] [ [12 13 14 15]
[ 6 7 8] [16 17 18 19]
[ 9 10 11]] [20 21 22 23] ] ]
# numpy.reshape()
import numpy as # Constructs 3D array
np a = a = np.arange(8).reshape(2, 2, 2)
np.arange(8) print("array reshaped to 3D :", a)
print("a : \n", a) Original array reshaped to 3D :
a : [0 1 2 3 4 5 6 7] [[[0 1]
# shape array with 2 rows & 4 [2 3]]
columns a =
np.arange(8).reshape(2, d with
4) 2 x 4
:
print("reshaped with 2 x 4 cols:", a) [ [4 5]
reshape[[0 1 2 3] [6 7]]]
[4 5 6 7]]
If an array is too large to be printed, NumPy automatically skips the central part
of the array and only prints the corners:
print(np.arange(10000)) print(np.arange(10000).reshape(100,100))
[ 0 1 2 ..., 9997 9998 9999]
[[ 0 1 2 ..., 97 98 99]
[ 100 101 102 ..., 197 198 199]
18
1-dimensional arrays can be indexed, sliced & iterated over, much like lists
& other Python sequences.
Array Indexing
The important thing to remember is that indexing in python starts at zero.
x1 = np.array([4, 3, 4, 4, 8, 4])
x1 # array([4, 3, 4, 4, 8, 4])
x1[0] #access value to index zero
4
x1[4] #access 5th value
8
x1[-1] #get the last value
4
x1[-2] #get the 2nd last value
8
#in a multidimensional array, we need to specify row & column index
x2
array([[3, 7, 5, 5],
[0, 1, 5, 9],
[3, 0, 5, 0]])
array([[12, 7, 5, 5],
[ 0, 1, 5, 9],
[ 3, 0, 5, 0]])
Array Slicing
Similar to Python lists, NumPy arrays can be sliced. Since arrays may be
mu ltidimensional, you must specify a slice for each dimension of the array:
x = np.arange(10)
x# array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
x[:5]#from start to 4th position
19
array([0, 1, 2, 3, 4])
x[4:]#from 4th position to last
array([4, 5, 6, 7, 8, 9])
x[4:7]#from 4th to 6th position
array([4, 5, 6])
x[ : : 2]#return elements at even place
array([0, 2, 4, 6, 8])
x[1::2]#return elements from 1st position step by 2
array([1, 3, 5, 7, 9])
x[::-1]#reverse the array
array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
Multidimensional arrays can have one index per axis. These indices are given in
a tuple separated by commas:
a = np.arange(10)
print a #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
s = slice(2,7,2) # start, stop, step
print a[s] # [2 4 6]
ndarray object is prepared by arange() function. Then a slice object is defined
with start, stop, & step values 2, 7, & 2 respectively. When this slice object is
passed to the ndarray, a part of it starting with index 2 up to 7 with a step of
2 is sliced.
a = np.arange(10)
print a #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b=a[2:7:2] # start : stop : step
print(b) # [2 4 6]
Data types
Every numpy array is a grid of elements of the same type. NumPy
provides a large set of numeric data types that you can use to construct
arrays.
NumPy tries to guess a data type when you create an array, but
functions that construct arrays usually also include an optional argument to
explicitly specify the datatype. Here is an example:
import numpy as np x = np.array([1,
x = np.array([1.0,
2]) print(x) 2.0])
#[1 2] print(x.dtype)
print(x.dtype) # float64
#int32 x = np.array([1, 2], dtype=np.int64)
print(x.dtype)
# int64
Array math
Basic mathematical functions operate elementwise on arrays, and are
available both as operator overloads and as functions in the numpy module:
x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)
# Elementwise addition; both produce the
array print(np.add(x, y))
[[ 6. 8.]
print(x + y)
[ 10. 12.]]
[[ 6. 8.]
20
[ 10. 12.]]
# Elementwise difference
print(np.subtract(x, y))
print(x - y) [[-4. -4.]
[[-4. -4.] [-4. -4.]]
[-4. -4.]]
# Element-wise product print(np.multiply(x, y))
print(x * y)
[[ 5.012.0]
[21.032.0]]
[[ 5.012.0]
[21.032.0]]
is element-wise multiplication, not matrix multiplication
*
Broadcasting
Trigonometric functions
Matplotlib
Data visualization is the presentation of data in a pictorial or graphical
format. Matplotlib is a Python 2D plotting library/package which
produces publication quality figures in a variety of hardcopy formats &
interactive environments across platforms.
One of the most popular uses for Python is data analysis.
Naturally, data scientists want a way to visualize their data. Either they
are wanted to see it for themselves to get a better grasp of the data, or
they want to display the data to convey their results to someone.
With Matplotlib, the most popular graphing and data visualization
module for Python, this is very simplistic to do.
22
In order to get the Matplotlib, you should first head to Matplotlib.org &
download the version that matches your version of Python. Once you have
Matplotlib installed, be sure to open up a terminal or a script, type:
import Matplotlib
Eg1:
from matplotlib import pyplot as plt plt.plot([1,2,3],[4,5,1]) #plot(x values, y values) plt.show(
Eg2:
from matplotlib import pyplot as plt
x = [5,8,10]
y = [12,16,6]
plt.plot(x,y)
plt.title('Epic Info')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
pythonprogramming.net/downloads/style.zip
Then, extract that, & move the styles folder within it to
c:/python34/matplotlib, where python34 is your python version. If you are
not on windows, just make sure the styles folder is in the root matplotlib
package folder.
Types Of
Plots Bar
Graph
Histogram
Scatter Plot
Area Plot
Pie Chart
#Bar graph
from matplotlib import pyplot as
plt
x1 = [5,8,10]
y1 = [12,16,6]
x2 = [6,9,11]
y2 = [6,15,7]
plt.bar
(x1,y1,color='b',align='center')
plt.bar(x2, y2, color='g',
align='center')
plt.title('Bar Plot')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
23
#scatter plot
from matplotlib import pyplot as plt
x1 = [5,8,10]
y1 = [12,16,6]
x2 = [6,9,11]
y2 = [6,15,7]
plt.scatter(x1, y1,color='r')
plt.scatter(x2, y2, color='g')
plt.title('Scatter plot')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
subplot()
Eg:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
plt.subplot(2, 1, 1) #2 rows,1 col,1st plot
plt.plot(x, y_sin)
plt.title('Sine')
plt.subplot(2, 1, 2) #2 rows,1 col,2nd plot
plt.plot(x, y_cos) plt.title('Cosine') plt.show()
SciPy(Scientific Python)
SciPy (pronounced "Sigh Pie") is an open source Python library used for
scientific computing & technical computing.
The SciPy library depends on Numpy, which provides convenient & fast
N- dimensional array manipulation.
SciPy is a library of algorithms and mathematical tools built to work with
NumPy arrays.
It provides many user-friendly & efficient numerical practices such as
routines for numerical integration & optimization.
SciPy contains modules for optimization, linear algebra, integration,
interpolation, special functions, FFT, signal and image processing, &
other tasks common in science & engineering.
Linear Equations
numpy.linalg.solve(a, b)
array.
b = np.array([10, 8, 3])
x = linalg.solve(a, b)