Home » Creating Arrays in NumPy tutorial with examples

Creating Arrays in NumPy tutorial with examples

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

Arrays are the core of NumPy, and they provide a powerful way to store and manipulate large datasets.

NumPy offers many methods to create arrays, from transforming Python lists into arrays to using specialized functions to generate arrays with specific patterns and values.

In this tutorial, we will cover:

  1. Creating Arrays from Lists and Tuples
  2. Creating Arrays with Default Values (zeros, ones, empty, full)
  3. Generating Sequences with arange and linspace
  4. Creating Identity and Diagonal Matrices
  5. Generating Random Arrays
  6. Using fromfunction for Advanced Array Creation

Let's dive into each method with examples.

1. Creating Arrays from Lists and Tuples

The simplest way to create a NumPy array is by converting a Python list or tuple using the np.array() function.

import numpy as np

# Creating a 1D array from a list
array_from_list = np.array([1, 2, 3, 4, 5])
print("1D Array from list:\n", array_from_list)

# Creating a 2D array from a list of lists
array_from_2d_list = np.array([[1, 2, 3], [4, 5, 6]])
print("\n2D Array from list of lists:\n", array_from_2d_list)

# Creating an array from a tuple
array_from_tuple = np.array((7, 8, 9))
print("\nArray from tuple:\n", array_from_tuple)

Output:

1D Array from list:
 [1 2 3 4 5]

2D Array from list of lists:
 [[1 2 3]
 [4 5 6]]

Array from tuple:
 [7 8 9]

2. Creating Arrays with Default Values (zeros, ones, empty, full)

NumPy provides several functions to quickly create arrays filled with default values. These are useful when initializing arrays that will later be modified.

Example 1: zeros()

Creates an array filled with zeros.

# Creating a 3x3 array of zeros
zeros_array = np.zeros((3, 3))
print("3x3 Array of zeros:\n", zeros_array)

Output:

3x3 Array of zeros:
 [[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

Example 2: ones()

Creates an array filled with ones.

# Creating a 2x4 array of ones
ones_array = np.ones((2, 4))
print("\n2x4 Array of ones:\n", ones_array)

Output:

2x4 Array of ones:
 [[1. 1. 1. 1.]
 [1. 1. 1. 1.]]

Example 3: empty()

Creates an array without initializing the values. It will contain whatever random values are in the allocated memory (useful for performance).

# Creating a 2x2 empty array
empty_array = np.empty((2, 2))
print("\n2x2 Empty array:\n", empty_array)

Example 4: full()

Creates an array filled with a specified value.

# Creating a 3x3 array filled with 7
full_array = np.full((3, 3), 7)
print("\n3x3 Array filled with 7:\n", full_array)

Output:

3x3 Array filled with 7:
 [[7 7 7]
 [7 7 7]
 [7 7 7]]

3. Generating Sequences with arange and linspace

NumPy offers functions to create arrays of numbers in a sequence.

Example 5: arange()

Similar to Python’s range() but returns an array. It generates values from start to stop with a specified step size.

# Array of numbers from 0 to 9
arange_array = np.arange(0, 10)
print("Array with arange from 0 to 9:\n", arange_array)

# Array with a step size
step_array = np.arange(0, 10, 2)
print("\nArray with arange from 0 to 10 with step 2:\n", step_array)

Output:

Array with arange from 0 to 9:
 [0 1 2 3 4 5 6 7 8 9]

Array with arange from 0 to 10 with step 2:
 [0 2 4 6 8]

Example 6: linspace()

Generates num evenly spaced values from start to stop.

# Array with 5 values between 0 and 1
linspace_array = np.linspace(0, 1, 5)
print("\nArray with linspace from 0 to 1 with 5 values:\n", linspace_array)

Output:

Array with linspace from 0 to 1 with 5 values:
 [0.   0.25 0.5  0.75 1.  ]

4. Creating Identity and Diagonal Matrices

Identity and diagonal matrices are commonly used in linear algebra and data science.

Example 7: eye()

Creates a 2D identity matrix with ones on the main diagonal and zeros elsewhere.

# 3x3 identity matrix
identity_matrix = np.eye(3)
print("3x3 Identity matrix:\n", identity_matrix)

Output:

3x3 Identity matrix:
 [[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

Example 8: diag()

Creates a matrix with a specified diagonal. You can also extract the diagonal from an existing array.

# Creating a diagonal matrix
diag_matrix = np.diag([1, 2, 3])
print("\nDiagonal matrix:\n", diag_matrix)

# Extracting the diagonal from an existing matrix
extracted_diag = np.diag(diag_matrix)
print("\nExtracted diagonal:", extracted_diag)

Output:

Diagonal matrix:
 [[1 0 0]
 [0 2 0]
 [0 0 3]]

Extracted diagonal: [1 2 3]

5. Generating Random Arrays

NumPy’s random module can generate arrays filled with random numbers, which is useful for data sampling, simulations, and testing.

Example 9: Random Values in [0, 1)

# 2x3 array with random values between 0 and 1
random_array = np.random.rand(2, 3)
print("Random array with values between 0 and 1:\n", random_array)

Example 10: Random Integers

# 2x2 array with random integers from 0 to 9
random_int_array = np.random.randint(0, 10, (2, 2))
print("\n2x2 Array with random integers between 0 and 9:\n", random_int_array)

Output:

Random array with values between 0 and 1:
 [[0.5488135  0.71518937 0.60276338]
 [0.54488318 0.4236548  0.64589411]]

2x2 Array with random integers between 0 and 9:
 [[7 3]
 [8 4]]

6. Using fromfunction for Advanced Array Creation

fromfunction() creates an array by executing a function over each coordinate, which is particularly useful for creating arrays with complex or patterned data.

Example 11: Creating an Array with a Mathematical Function

# Create a 3x3 array where each value is the sum of its row and column indices
def sum_indices(i, j):
    return i + j

array_from_function = np.fromfunction(sum_indices, (3, 3), dtype=int)
print("Array created with fromfunction:\n", array_from_function)

Output:

Array created with fromfunction:
 [[0 1 2]
 [1 2 3]
 [2 3 4]]
  • Explanation: fromfunction(sum_indices, (3, 3)) applies the sum_indices function to each coordinate in a 3×3 grid, where each element is calculated as the sum of its row and column indices.

Example 12: Creating a Checkerboard Pattern

# Function for creating a checkerboard pattern
def checkerboard(i, j):
    return (i + j) % 2

checkerboard_array = np.fromfunction(checkerboard, (8, 8), dtype=int)
print("\n8x8 Checkerboard pattern:\n", checkerboard_array)

Output:

8x8 Checkerboard pattern:
 [[0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0

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

Summary of Array Creation Methods in NumPy

Method Description
array Converts Python lists or tuples to NumPy arrays.
zeros Creates an array filled with zeros.
ones Creates an array filled with ones.
empty Creates an uninitialized array.
full Creates an array filled with a specified value.
arange Generates a sequence of numbers with a specified step size.
linspace Generates evenly spaced values over a specified range.
eye Creates an identity matrix.
diag Creates a diagonal matrix or extracts the diagonal of an existing matrix.
random Generates arrays filled with random values.
fromfunction Applies a function to create patterned arrays.

Conclusion

In this tutorial, we explored various ways to create arrays in NumPy, including:

  • Converting lists and tuples to arrays.
  • Using default values like zeros, ones, and custom values.
  • Generating sequences and special matrices.
  • Creating random arrays and arrays from functions for complex patterns.

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