Home » A Guide to the NumPy ndarray Object in Python

A Guide to the NumPy ndarray Object in Python

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

The NumPy ndarray (N-dimensional array) is the core data structure in the NumPy library.

It is a powerful and efficient way to store and manipulate large amounts of data, allowing for fast element-wise operations and manipulation across multiple dimensions.

In this tutorial, we will cover:

  1. Creating ndarray Objects
  2. Basic Properties of ndarray
  3. Indexing and Slicing in ndarray
  4. Basic Operations on ndarray
  5. Reshaping and Resizing ndarray
  6. Broadcasting in ndarray

Let’s dive in with examples for each section!

1. Creating ndarray Objects

You can create ndarray objects in various ways, including from lists, using built-in NumPy functions, or by generating random values.

Creating an ndarray from a List

import numpy as np

# Creating a 1D ndarray
arr1 = np.array([1, 2, 3, 4])
print("1D Array:\n", arr1)

# Creating a 2D ndarray
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
print("\n2D Array:\n", arr2)

Output:

1D Array:
 [1 2 3 4]

2D Array:
 [[1 2 3]
 [4 5 6]]

Creating ndarray with NumPy Functions

NumPy provides functions like zeros(), ones(), arange(), and linspace() to create ndarray objects with specific patterns.

# Array of zeros
zeros = np.zeros((2, 3))
print("Zeros Array:\n", zeros)

# Array of ones
ones = np.ones((2, 3))
print("\nOnes Array:\n", ones)

# Array of evenly spaced values
arr = np.arange(0, 10, 2)
print("\nArray using arange:\n", arr)

# Array with values from a linear space
linspace_arr = np.linspace(0, 1, 5)
print("\nArray using linspace:\n", linspace_arr)

2. Basic Properties of ndarray

The ndarray object has several useful properties, including shape, size, and data type.

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

# Shape of the array
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

3. Indexing and Slicing in ndarray

Indexing and slicing in ndarray is similar to Python lists but more powerful, especially for multidimensional arrays.

Indexing

arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])

# Access single element
print("Element at (0,1):", arr[0, 1])

Output:

Element at (0,1): 20

Slicing

# Slicing rows and columns
print("Sliced Array:\n", arr[:2, 1:])

Output:

Sliced Array:
 [[20 30]
 [50 60]]

Boolean Indexing

Boolean indexing allows you to filter elements that satisfy a particular condition.

# Filter elements greater than 50
filtered_arr = arr[arr > 50]
print("Filtered Array:", filtered_arr)

Output:

Filtered Array: [60 70 80 90]

4. Basic Operations on ndarray

NumPy supports element-wise arithmetic operations and various mathematical functions.

Arithmetic Operations

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

# Element-wise addition
print("Addition:\n", arr + 10)

# Element-wise multiplication
print("Multiplication:\n", arr * 2)

Output:

Addition:
 [11 12 13 14]

Multiplication:
 [2 4 6 8]

Operations with Another Array

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

# Element-wise addition
print("Addition:\n", arr1 + arr2)

# Element-wise multiplication
print("Multiplication:\n", arr1 * arr2)

Output:

Addition:
 [5 7 9]

Multiplication:
 [ 4 10 18]

Aggregation Functions

NumPy provides various aggregation functions like sum(), mean(), max(), and min().

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

5. Reshaping and Resizing ndarray

You can change the shape of an ndarray without changing the data.

Reshaping an Array

arr = np.arange(1, 7)  # Array from 1 to 6
reshaped_arr = arr.reshape(2, 3)
print("Reshaped Array:\n", reshaped_arr)

Output:

Reshaped Array:
 [[1 2 3]
 [4 5 6]]

Flattening an Array

flatten() and ravel() can convert a multi-dimensional array into a 1D array.

# Flattening a 2D array to 1D
flat_arr = reshaped_arr.flatten()
print("Flattened Array:", flat_arr)

Output:

Flattened Array: [1 2 3 4 5 6]

Resizing an Array

resize() changes the shape of an array in-place and can adjust the array’s size.

# Resizing an array
arr = np.array([[1, 2], [3, 4]])
arr.resize(2, 3)
print("Resized Array:\n", arr)

Output:

Resized Array:
 [[1 2 3]
 [3 4 0]]

6. Broadcasting in ndarray

Broadcasting allows you to perform arithmetic operations on arrays of different shapes, extending the smaller array to match the larger one.

Example of Broadcasting

arr1 = np.array([1, 2, 3])
arr2 = np.array([[10], [20], [30]])

# Broadcasting addition
result = arr1 + arr2
print("Broadcasted Addition:\n", result)

Output:

Broadcasted Addition:
 [[11 12 13]
 [21 22 23]
 [31 32 33]]

Explanation: arr1 (1D) is broadcasted across each row of arr2 (2D), allowing element-wise addition between arrays of different shapes.

Summary of Key ndarray Concepts

Concept Description
Array Creation Create arrays using array(), zeros(), ones(), arange(), and linspace().
Array Properties Use shape, ndim, size, and dtype to inspect arrays.
Indexing and Slicing Select data using indexing and slicing, similar to Python lists.
Array Operations Perform arithmetic, Boolean indexing, and aggregation functions.
Reshaping and Resizing Change the shape of arrays with reshape(), flatten(), and resize().
Broadcasting Perform operations on arrays with different shapes, thanks to broadcasting.

Conclusion

In this tutorial, we explored the basics of the NumPy ndarray object, including:

  • Creating ndarray objects from various sources.
  • Understanding the basic properties and structure of ndarray.
  • Using indexing, slicing, and Boolean indexing to access elements.
  • Performing element-wise operations, reshaping arrays, and understanding broadcasting.

The ndarray object is the foundation for data manipulation and numerical computation in Python.

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