Getting Started with Numpy and Matplotlib python | PYTHOLABS
Tags: Numpy, Data Science, Pytholabs, Matplotlib, Python

Today’s post will focus on introducing NumPy and Matplotlib to beginners where you’ll learn how to create a NumPy array, use broadcasting, access values, manipulate arrays, and much more.

NumPy is, just like SciPy, Scikit-Learn , etc. one of the packages that you just can’t miss when you’re learning data science, mainly because this library provides you with an array data structure that holds some benefits over Python lists, such as: being more compact, faster access in reading and writing items, being more convenient and more efficient.

>>> %timeit [i**2 for i in L] 441 µs ± 3.24 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

this list comprehension takes 441 microseconds to compute. whereas numpy array object takes 5.2 microseconds which is around 100x faster :

>>> %timeit np.arange(1000)**2 5.22 µs ± 189 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Before you can start to try out these NumPy arrays for yourself, you first have to make sure that you have it installed locally (assuming that you’re working on your pc). If you have the Python library already available, go ahead and skip this section :)

If you’re working on Windows, make sure that you have added Python to the PATH environment variable. Then, don’t forget to install a package manager, such as pip, which will ensure that you’re able to use Python’s open-source libraries.

$ pip install numpy

There are many types of arrays like 1-d,2-d,3-d, etc :

*Default datatype of np arrays is “float64”

>>> a = np.array([0, 1, 2, 3])

array([0, 1, 2, 3])

>>> a.ndim

1

>>> a.shape

(4,)

>>> len(a)

4

2. 2-D array :

>>> b = np.array([[0, 1, 2], [3, 4, 5]])

array([[0, 1, 2],

[3, 4, 5]])

>>> b.ndim

2

>>> b.shape

(2, 3)

>>> len(b)

2 >>> a = np.arange(10) # 0 .. n-1 (!)

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

2. By a number of points:

>>> c = np.linspace(0, 1, 6) # start, end, num-points

array([0. , 0.2, 0.4, 0.6, 0.8, 1. ]) >>> d = np.linspace(0, 1, 5, endpoint=False)

array([0. , 0.2, 0.4, 0.6, 0.8])

3. Common arrays :

>>> a = np.ones((3, 3)) # reminder: (3, 3) is a tuple

array([[1., 1., 1.],

[1., 1., 1.],

[1., 1., 1.]]) >>> b = np.zeros((2, 2))

array([[0., 0.],

[0., 0.]])

4. np.random : random numbers (Mersenne Twister PRNG):

>>> a = np.random.rand(4) # uniform in [0, 1]

array([0.88533653, 0.79770426, 0.17104927, 0.05253928]) >>> b = np.random.randn(4) # Gaussian

array([-0.88773888, 0.69960706, -1.71071659, 1.31333033])

Matplotlib is probably the most used Python package for 2D-graphics. It provides both a quick way to visualize data from Python and publication-quality figures in many formats.

>>> import matplotlib.pyplot as plt # the tidy way %matplotlib inline

And then use (note that you have to use show explicitly if you have not enabled interactive plots with %matplotlib ):

>>> plt.plot(x, y) # line plot

>>> plt.show() # <-- shows the plot (not needed with interactive plots)

It is of two types:

>>> x = np.linspace(0, 3, 20)

>>> y = np.linspace(0, 9, 20)

>>> plt.plot(x, y) # line plot

>>> plt.plot(x, y, 'o') # dot plot

import numpy as np

import matplotlib.pyplot as plt # Create a figure of size 8x6 inches, 80 dots per inch

plt.figure(figsize=(8, 6), dpi=80) # Create a new subplot from a grid of 1x1

plt.subplot(1, 1, 1) X = np.linspace(-np.pi, np.pi, 256, endpoint=True)

C, S = np.cos(X), np.sin(X) # Plot cosine with a blue continuous line of width 1 (pixels)

>>> plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-") # Plot sine with a green continuous line of width 1 (pixels)

>>> plt.plot(X, S, color="green", linewidth=1.0, linestyle="-") # Set x limits

>>> plt.xlim(-4.0, 4.0) # Set x ticks

>>> plt.xticks(np.linspace(-4, 4, 9, endpoint=True)) # Set y limits

>>> plt.ylim(-1.0, 1.0) # Set y ticks

>>> plt.yticks(np.linspace(-1, 1, 5, endpoint=True)) # Save figure using 72 dots per inch

# plt.savefig("exercise_2.png", dpi=72) # Show result on screen

>>> plt.show()

2. 2-D plotting:

>>> image = np.random.rand(30, 30)

>>> plt.imshow(image, cmap=plt.cm.hot)

>>> plt.colorbar()

Besides mathematical operations, you might also consider taking just a part of the original array (or the resulting array) or just some array elements to use in further analysis or other operations. In such case, you will need to subset, slice and/or index your arrays.

If you have no clue at all on how these operations work, it suffices for now to know these two basic things:

· You use square brackets [] as the index operator, and

>>> a = np.array([1,2,3,4,5])

>>> a[1]

2 >>> a[0:3]

array([1,2,3])

· Generally, you pass integers to these square brackets, but you can also put a colon: or a combination of the colon with integers in it to designate the elements/rows/columns you want to select.

Visit our site: https://pytholabs.com/

Our machine learning course Enroll now!

Reference: https://scipy-lectures.org/intro/index.html