Welcome to this lesson on understanding Numpy arrays! Today, we will be focusing on numerical computations with Numpy, specifically around the creation, manipulation, and operations of Numpy arrays.
Numpy, short for Numerical Python, is an essential library for performing numerical computations in Python. It has support for arrays (like lists in Python, but can store items of the same type), multidimensional arrays, matrices, and a large collection of high-level mathematical functions.
In the world of data manipulation using Python, understanding and being able to use Numpy arrays allows us to efficiently manage numerical data.
The most common way to create a Numpy array is by using the numpy.array() function. You can pass any sequence-like object into this function, and it will be converted into an array. Let's convert a regular Python list into a Numpy array:
Executing these lines creates a one-dimensional Numpy array np_array with the same elements as our regular Python list py_list.
We can also create two-dimensional arrays (similar to matrices). Let's convert a list of lists into a 2D Numpy array:
We now have a two-dimensional Numpy array np_array_2d, with each sub-list of py_list_2d as a row in np_array_2d.
Numpy arrays come equipped with several attributes for gaining more insights:
ndimtells us the number of dimensions of the array.shapegives us the size of each dimension.sizetells us the total number of elements in the array.dtypetells us the data type of the elements in the array.
Let's create a 2D array and use these attributes:
After running these lines, we see that np_array is a 2D array (since ndim returns the value 2), has 2 rows and 3 columns (shape returns the tuple (2, 3)), contains 6 elements (size returns 6), and is of integer type (dtype returns 'int64').
