Home » Getting Started with NumPy in Python: A Beginner’s Tutorial

Getting Started with NumPy in Python: A Beginner’s Tutorial

Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Programmer II [1Z0-816] Practice Tests
1 Year Subscription
Oracle Java Certification
Java SE 11 Developer (Upgrade) [1Z0-817]
Spring Framework Basics Video Course

NumPy (Numerical Python) is a powerful Python library for numerical computing.

It provides support for large, multi-dimensional arrays and matrices, along with a wide range of mathematical functions.

NumPy is often the foundation for scientific computing in Python and is a key component of libraries like Pandas and TensorFlow.

In this tutorial, we will cover:

  1. Installing NumPy
  2. Creating NumPy Arrays
  3. Array Properties and Attributes
  4. Array Indexing and Slicing
  5. Basic Array Operations
  6. Common Mathematical Functions
  7. Broadcasting

Let’s dive into NumPy step-by-step!

1. Installing NumPy

To install NumPy, use the following command:

pip install numpy

Once installed, you can import it in your Python script or Jupyter Notebook:

import numpy as np

2. Creating NumPy Arrays

A NumPy array is a grid of values, all of the same type, and indexed by a tuple of non-negative integers. NumPy arrays are more efficient than Python lists, making them ideal for numerical calculations.

Creating an Array from a List

import numpy as np

# Creating a 1D array
arr1 = np.array([1, 2, 3, 4, 5])
print(arr1)

Output:

[1 2 3 4 5]

Creating a 2D Array

# Creating a 2D array
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2)

Output:

[[1 2 3]
 [4 5 6]]

Using arange() and linspace()

  • arange(start, stop, step): Generates values from start to stop (exclusive) with the given step.
  • linspace(start, stop, num): Generates num evenly spaced values from start to stop (inclusive).
# Using arange
arr3 = np.arange(0, 10, 2)
print(arr3)

# Using linspace
arr4 = np.linspace(0, 1, 5)
print(arr4)

Output:

[0 2 4 6 8]
[0.   0.25 0.5  0.75 1.  ]

Creating Arrays with Zeros, Ones, and Identity Matrix

# Array of zeros
zeros = np.zeros((2, 3))
print(zeros)

# Array of ones
ones = np.ones((3, 2))
print(ones)

# Identity matrix
identity = np.eye(3)
print(identity)

Output:

[[0. 0. 0.]
 [0. 0. 0.]]

[[1. 1.]
 [1. 1.]
 [1. 1.]]

[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

3. Array Properties and Attributes

Understanding an array’s shape, size, and data type is crucial for manipulating and working with data in NumPy.

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

# Shape of the array (rows, columns)
print("Shape:", arr.shape)

# Number of dimensions
print("Number of dimensions:", arr.ndim)

# Total number of elements
print("Size:", arr.size)

# Data type of elements
print("Data type:", arr.dtype)

Output:

Shape: (2, 3)
Number of dimensions: 2
Size: 6
Data type: int64

4. Array Indexing and Slicing

NumPy arrays support indexing and slicing, which is similar to lists but with more flexibility for multi-dimensional arrays.

Indexing

# Creating a 2D array
arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])

# Accessing a single element (first row, second column)
print(arr[0, 1])

Output:

20

Slicing

# Slicing rows and columns
print(arr[:2, 1:])  # First two rows, columns from index 1 onward

Output:

[[20 30]
 [50 60]]
  • Explanation: [:2, 1:] selects rows 0 and 1 and columns from index 1 onward.

Boolean Indexing

You can use Boolean conditions to filter elements in an array.

# Get elements greater than 50
print(arr[arr > 50])

Output:

[60 70 80 90]

5. Basic Array Operations

NumPy supports element-wise arithmetic operations, which are performed much faster than using loops.

Arithmetic Operations

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

# Element-wise addition
print(arr + 10)

# Element-wise multiplication
print(arr * 2)

Output:

[11 12 13 14]
[2 4 6 8]

Array Operations with Another Array

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

# Element-wise addition
print(arr1 + arr2)

# Element-wise multiplication
print(arr1 * arr2)

Output:

[5 7 9]
[ 4 10 18]

Aggregation Functions

NumPy provides many functions for aggregating values in an array.

# Aggregation functions
arr = np.array([1, 2, 3, 4, 5])

print("Sum:", arr.sum())
print("Mean:", arr.mean())
print("Max:", arr.max())
print("Min:", arr.min())

Output:

Sum: 15
Mean: 3.0
Max: 5
Min: 1

6. Common Mathematical Functions

NumPy provides many mathematical functions for element-wise calculations on arrays.

Trigonometric Functions

arr = np.array([0, np.pi / 2, np.pi])

# Sine and cosine
print("Sine:", np.sin(arr))
print("Cosine:", np.cos(arr))

Output:

Sine: [0. 1. 0.]
Cosine: [ 1.  0. -1.]

Exponential and Logarithmic Functions

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

# Exponential
print("Exponential:", np.exp(arr))

# Natural logarithm
print("Log:", np.log(arr))

Output:

Exponential: [ 2.71828183  7.3890561  20.08553692]
Log: [0.         0.69314718 1.09861229]

7. Broadcasting

Broadcasting is a powerful feature in NumPy that allows operations on arrays with different shapes. This is especially useful when performing arithmetic between arrays of different dimensions.

Example of Broadcasting

# Creating a 1D and 2D array
arr1 = np.array([1, 2, 3])
arr2 = np.array([[10], [20], [30]])

# Adding the arrays
result = arr1 + arr2
print(result)

Output:

[[11 12 13]
 [21 22 23]
 [31 32 33]]
  • Explanation: arr1 is broadcasted across each row of arr2, resulting in element-wise addition for each row.

Summary of Key Concepts in NumPy

Concept Description
Array Creation Create arrays using array(), arange(), linspace(), zeros(), and ones().
Array Properties Use shape, size, ndim, and dtype to inspect arrays.
Indexing and Slicing Select data using single/multi-dimensional indexing and slicing.
Array Operations Perform arithmetic operations like addition, subtraction, multiplication.
Aggregation Functions Use sum(), mean(), max(), etc. for quick calculations.
Broadcasting Perform operations on arrays of different shapes.

Conclusion

In this tutorial, we covered the basics of NumPy in Python, including:

  • Installing NumPy and creating arrays.
  • Understanding array properties, indexing, slicing, and Boolean indexing.
  • Performing basic arithmetic operations and applying mathematical functions.
  • Using broadcasting for operations on arrays of different shapes.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More