Python Tutorial: Arrays & plotting

preview_player
Показать описание

---
You’ve learned about basic Python data structures, but coming from MATLAB, you must be wondering where the matrices and plotting functions are.

In Python, MATLAB-like matrices are called “arrays.” Arrays are implemented using the NumPy package, which is short for “numerical Python.” Arrays are the foundation for all data science in Python.

Like MATLAB’s matrices, NumPy’s matrices can have 1, 2, 3, or more dimensions. And every element in the array must be of the same type. All integers or all floats, for example. There are some practical differences, however, particularly in how you access data stored in NumPy arrays.

First, is the syntax for indexing into the array. In MATLAB, you are used to using parentheses, however, in Python, we use square brackets for indexing. In this example, I have a NumPy array in the variable “arr,” and you can see that I’m using square brackets with an integer for the index I want to get out of the array.

The second big difference is the indexing itself. In Python, the index “2” will return the third element in the array. This is because Python uses “zero-indexing,” that is, the first element is accessed with “0”, the second with “1”, the third with “2” and so on.

One way to think about it is if MATLAB is an American elevator, where the ground floor starts with “1”, Python is a European elevator, where “1” denotes the level above the ground floor.

This is likely very unintuitive coming from MATLAB, but with practice, it’s easy to get used to it.

The final element in an array can be accessed with its index from 0 or "-1", which works like MATLAB's "end."

For visualizing your data, there are multiple packages to choose from in Python. The most popular and the one we are going to use most is called "Matplotlib.” Lucky for you, Matplotlib was designed to work similarly to plotting in MATLAB, so it shares many of the functions for plotting and customizing your plots that you are familiar with.

First, the package needs to be imported. Most plotting functions live in Matplotlib's pyplot module, which is typically imported to the variable "plt," like so.

Once imported, the "pyplot" module contains many functions that work similarly to their MATLAB counterparts.

figure() creates a new figure to plot in.

plot() creates line plots.

xlabel() and ylabel() add labels to the x- and y- axes, respectively.

Importantly, we need to explicitly call show() to display any plots that we create.

Now that you know how to use NumPy arrays to store data and Matplotlib to make plots, you're ready to start practicing.

#Python #PythonTutorial #DataCamp #Python #MATLAB #Arrays #plotting
Рекомендации по теме
visit shbcf.ru