Creating and Using Python NumPy Arrays

PythonPythonBeginner
Practice Now

Introduction

This lab provides a step-by-step guide to creating and using NumPy arrays. NumPy arrays are multidimensional, grid-like structures used for scientific computing and data analysis in Python. They have several advantages over Python lists, including faster computation, easier manipulation, and better memory management.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) linux(("`Linux`")) -.-> linux/PackagesandSoftwaresGroup(["`Packages and Softwares`"]) numpy(("`NumPy`")) -.-> numpy/ArrayManipulationGroup(["`Array Manipulation`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) numpy(("`NumPy`")) -.-> numpy/ArrayBasicsGroup(["`Array Basics`"]) numpy(("`NumPy`")) -.-> numpy/IndexingandSlicingGroup(["`Indexing and Slicing`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") linux/PackagesandSoftwaresGroup -.-> linux/pip("`Python Package Installing`") numpy/ArrayManipulationGroup -.-> numpy/reshape("`Reshape`") numpy/ArrayManipulationGroup -.-> numpy/transpose("`Transpose and Axis Swap`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") numpy/ArrayBasicsGroup -.-> numpy/1d_array("`1D Array Creation`") numpy/ArrayBasicsGroup -.-> numpy/multi_array("`Multi-dimensional Array Creation`") numpy/ArrayBasicsGroup -.-> numpy/data_array("`Data to Array`") numpy/ArrayBasicsGroup -.-> numpy/shape_dim("`Shapes and Dimensions`") numpy/ArrayBasicsGroup -.-> numpy/attr("`Basic Attributes`") numpy/IndexingandSlicingGroup -.-> numpy/bool_idx("`Boolean Indexing`") numpy/IndexingandSlicingGroup -.-> numpy/fancy_idx("`Fancy Indexing`") subgraph Lab Skills python/comments -.-> lab-86402{{"`Creating and Using Python NumPy Arrays`"}} linux/pip -.-> lab-86402{{"`Creating and Using Python NumPy Arrays`"}} numpy/reshape -.-> lab-86402{{"`Creating and Using Python NumPy Arrays`"}} numpy/transpose -.-> lab-86402{{"`Creating and Using Python NumPy Arrays`"}} python/lists -.-> lab-86402{{"`Creating and Using Python NumPy Arrays`"}} python/tuples -.-> lab-86402{{"`Creating and Using Python NumPy Arrays`"}} python/importing_modules -.-> lab-86402{{"`Creating and Using Python NumPy Arrays`"}} python/numerical_computing -.-> lab-86402{{"`Creating and Using Python NumPy Arrays`"}} python/build_in_functions -.-> lab-86402{{"`Creating and Using Python NumPy Arrays`"}} numpy/1d_array -.-> lab-86402{{"`Creating and Using Python NumPy Arrays`"}} numpy/multi_array -.-> lab-86402{{"`Creating and Using Python NumPy Arrays`"}} numpy/data_array -.-> lab-86402{{"`Creating and Using Python NumPy Arrays`"}} numpy/shape_dim -.-> lab-86402{{"`Creating and Using Python NumPy Arrays`"}} numpy/attr -.-> lab-86402{{"`Creating and Using Python NumPy Arrays`"}} numpy/bool_idx -.-> lab-86402{{"`Creating and Using Python NumPy Arrays`"}} numpy/fancy_idx -.-> lab-86402{{"`Creating and Using Python NumPy Arrays`"}} end

Installing NumPy

Before we can begin creating and using NumPy arrays, it is necessary to install the NumPy package. This can be done using the following command:

!pip install numpy

Creating a NumPy Array

To create a NumPy array, we can use the numpy.array() function. We can pass a list, tuple, or any array-like object to this function, and it will convert it into a NumPy array. The dtype parameter can be used to explicitly define the data type of the array.

import numpy as np

## create a 1-dimensional NumPy array
arr1 = np.array([1, 2, 3])

## create a 2-dimensional NumPy array
arr2 = np.array([[1, 2, 3],[4, 5, 6]])

Checking the Shape and Dimensions of a NumPy Array

We can use the shape and ndim attributes of a NumPy array to check its shape and dimensions, respectively. The shape attribute returns a tuple with the number of elements in each dimension of the array, while the ndim attribute returns the number of dimensions in the array.

import numpy as np

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

print(arr.shape) ## output: (2, 3)
print(arr.ndim) ## output: 2

Accessing Elements of a NumPy Array

We can access elements of a NumPy array using indexing and slicing, just like with Python lists. The index of a NumPy array always starts at 0.

import numpy as np

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

print(arr[0, 1]) ## output: 2
print(arr[:, 1]) ## output: array([2, 5])

Performing Operations on NumPy Arrays

NumPy arrays support many different operations, such as arithmetic operations, aggregation functions, and logical operations. For example, we can use the sum() and mean() functions to calculate the sum and mean of the elements of a NumPy array:

import numpy as np

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

print(arr.sum()) ## output: 21
print(arr.mean()) ## output: 3.5

Reshaping and Transposing NumPy Arrays

We can reshape a NumPy array using the reshape() function. This function takes a tuple of the desired shape as its argument. We can also transpose a NumPy array using the transpose() or T attribute.

import numpy as np

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

## reshape array to 3 rows and 2 columns
arr_reshaped = arr.reshape((3, 2))

## transpose array
arr_transposed = arr.transpose()
arr_T = arr.T

print(arr_reshaped) ## output: array([[1, 2],[3, 4],[5, 6]])
print(arr_transposed) ## output: array([[1, 4],[2, 5],[3, 6]])
print(arr_T) ## output: array([[1, 4],[2, 5],[3, 6]])

Summary

In this lab, we learned how to create and use NumPy arrays in Python. We covered the basic steps of creating an array, checking its shape and dimensions, accessing its elements, performing operations on it, and reshaping and transposing it. With these skills, we can efficiently work with multidimensional arrays for scientific computing and data analysis.

Other Python Tutorials you may like