Exploring Python NumPy: NumPy Array Part 2

Table of Contents

Introduction

Welcome to the second installment of our Python NumPy series! In this segment, we delve deeper into the world of NumPy arrays in Python. We’re about to unveil the what and how of these dynamic arrays. Transitioning from the foundations we laid in the first part, brace yourself for an insightful exploration. So, let’s embark on this journey to understand the essence and creation of NumPy arrays, building upon the knowledge we’ve gathered so far.

NumPy Arrays

In this section, let’s delve into the realm of NumPy arrays and master the art of crafting these potent data structures. NumPy arrays stand as the cornerstone of the library, empowering us to handle and manipulate numerical data with finesse. We’ll plunge into diverse techniques for creating NumPy arrays, revealing the expansive flexibility they bestow upon data manipulation across dimensions and shapes. So, without further ado, let’s embark on our journey to explore, create, and harness the capabilities of NumPy arrays.

Creating NumPy Arrays:

NumPy provides several ways to create arrays. Here are some common methods:

NumPy Array From a Python list:

To create a NumPy Array, simply pass a Python list or nested lists to the np.array() function.

05 (1)
Explanation for the program:

In the provided program, we begin by importing the NumPy library using the line ‘import numpy as np’, enabling us to wield NumPy’s functionalities.

Next, a Python list named my_list holds values [1, 2, 3, 4, 5]. We convert this list into a NumPy array by passing it as an np.array() function argument, creating array arr.

To examine the array, we use print() to display arr, revealing contents [1, 2, 3, 4, 5]. The type() function identifies the array’s data type with print(type(arr)), showing <class ‘numpy.ndarray’>, indicating arr is a NumPy array.

We access and print the first element via print(arr[0]), yielding 1, as Python array indexing starts at 0. Similarly, print(type(arr[0])) determines the first element’s data type, displaying <class ‘numpy.int64’> for a 64-bit integer.

This program showcases NumPy array creation from a Python list and basic operations to access array elements and their data types.

NumPy Array From a Python Tuple:

In addition to Python lists, NumPy empowers us to form arrays from tuples as well. Tuples, akin to lists, possess immutability, implying their elements remain unaltered post-definition. Now, let’s delve into the process of crafting NumPy arrays out of tuples.

Here’s an example:

06 (1)
Explanation for the program:

This program initiates by importing the NumPy library through import numpy as np. A tuple named my_tuple is established, holding values (1, 2, 3, 4, 5). For the transformation of the tuple into a NumPy array, we employ my_tuple as an argument within the np.array() function, consequently producing array arr.

Creating Multi-Dimensional Arrays using NumPy

NumPy empowers us to forge multi-dimensional arrays, providing the capability to depict and manipulate data across diverse dimensions. These arrays can encompass various numbers of dimensions, often labeled as axes. Now, let’s embark on the journey of crafting multi-dimensional arrays using NumPy.

07 (1)
Explanation for the program:

We define a Python list, my_list, containing three sublists that depict rows of a matrix. To forge a multi-dimensional array from my_list, we feed it as an np.array() function argument. The outcome, array arr, symbolizes a 3×3 matrix. Creating multi-dimensional arrays in NumPy empowers us to handle intricate data structures like matrices or higher-dimensional tensors. Efficient execution of diverse operations becomes feasible. NumPy furnishes abundant functions and methods to manipulate and analyze multi-dimensional arrays, establishing it as a potent instrument for scientific computing and data analysis.

Creating NumPy Arrays using arange()

To discretize data and craft NumPy arrays featuring evenly spaced values, one can utilize the arange() function. This function generates a one-dimensional array that encompasses values within a designated interval.

Syntax:

08 (1)
  • start: Specify the interval’s start value, inclusive in the array. It’s optional, with the default being 0.
  • stop: Set the interval’s end value, not included in the array. This parameter is required.
  • step: Determine the spacing between successive values in the array. It’s optional, defaulting to 1. The step can also be a decimal or floating-point number, allowing non-integer increments.
  • dtype: Indicate the array element’s data type. It’s optional, and if omitted, NumPy infers it from start, stop, and step.

By adjusting start, stop, and step (and optionally specifying dtype), you wield precise control over the array’s value range and spacing.

Example 1:

Here’s an example of creating a one-dimensional array using arange():

09 (1)
Explanation:

This instance showcases the arange() function’s usage to construct an array named arr, housing values from 1 to 9 (excluding 10), with an increment of 2. The resulting array becomes [1, 3, 5, 7, 9]. Harnessing arange()’s adaptability, we can fashion arrays with diverse setups, including tailoring start, stop, and step values. This versatility empowers us to discretize data effectively, yielding tailor-made one-dimensional arrays aligned with our precise requirements.

Example 2:

Here’s a second example demonstrating the arange() function with all arguments, including dtype, specified:

10 (2)
Explanation:

In this example, we import the NumPy arrays library using import numpy as np.

We use the arange() function to create an array named arr with the following arguments:

  • start: 2.5
  • stop: 10.5 (exclusive)
  • step: 0.5
  • dtype: float (to specify the data type of the array elements as floating-point numbers)

The resulting array will be [2.5, 3.0, 3.5, 4.0, …, 10.0, 10.5], where each consecutive value is incremented by 0.5.

This example illustrates the utilization of arange() to establish an array with defined start, stop, and step values. Additionally, we explicitly designate the array element data type as float. The versatile nature of the arange() function empowers us to fabricate arrays tailored to desired setups, essential for diverse numerical computations and data processing undertakings.

Creating Multidimensional NumPy Arrays using arange()

Within NumPy arrays, the creation of multi-dimensional arrays can be accomplished by intertwining the arange() function with the reshape() method. The arange() function generates a one-dimensional array of uniformly spaced values, while the reshape() method permits the transformation of this array into a specified multi-dimensional configuration. Join us as we delve into the process of crafting multi-dimensional arrays through this dynamic approach.

Syntax:

array.reshape((rows, columns))

Example:
11 (2)
Explanation:

In this instance, we initiate by importing the NumPy library via import numpy as np. Employing the arange() function, we shape a one-dimensional array housing values from 0 to 11 (inclusive), yielding [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]. Subsequently, we execute the reshape() method on the array, using (3, 4) as parameters to mold it into a 3×4 matrix. For an insight into the generated multi-dimensional array, the print() function comes into play, revealing its contents with print(arr).

Creating NumPy Array using linespace() Function:

In NumPy, the linspace() function is used to generate arrays with equally spaced values within a specified interval. The linspace() function takes the start and end points of the interval and the number of desired elements as arguments, and it returns an array with evenly distributed values.

Syntax:

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

Let’s delve into the distinct parameters of the linspace() function:

  • start (required): Represents the interval’s starting value.
  • stop (required): Signifies the interval’s concluding value.
  • num (optional): Determines the count of equidistant values within the interval. The default is 50.
  • endpoint (optional): When set to True (default), the generated array includes the end value. When set to False, it excludes the end value.
  • retstep (optional): If set to True, the function furnishes the step size between consecutive values as a second output. Default is False.
  • dtype (optional): Specifies the data type of resulting array elements. Absent input prompts automatic determination.

Here’s an example of using the linspace() function to create an array:

12 (2)
Explanation:

In the preceding example, we import the NumPy library through import numpy as np. By employing the linspace() function, we shape an array named arr with values evenly spaced between 0 and 10. The num parameter is configured to 20, signifying our intent for 20 elements in the resultant array. To scrutinize the array, we utilize the print() function to showcase its contents via print(arr). The outcome manifests as an array featuring 20 uniformly distributed values spanning 0 to 10. The prowess of the linspace() function emerges when there’s a necessity to craft arrays with a distinct quantity of equidistant values encompassing an interval. Its prevalence extends across numerous scientific, numerical computations, and visualization endeavors, bolstering tasks like plotting.

Creating a NumPy Array or Zeroes:

Within NumPy, the zeros() function finds its purpose in crafting arrays laden with zeros. This versatile function enables the definition of the array’s shape and data type. The outcome is an array primed with zero values across all its elements.

Syntax:

numpy.zeros(shape, dtype=float, order=’C’)

Let’s delve into the distinctive parameters of the zeros() function:

  • shape (required): Specifies the array’s configuration. It can be an integer denoting elements in a one-dimensional array or a tuple of integers signifying multi-dimensional array dimensions.
  • dtype (optional): Dictates the resulting array’s element data type. Default is float, with other common types like int (integer) and bool (boolean).
  • order (optional): Determines the array’s memory arrangement. The default is ‘C’, representing C-style (row-major) order. Alternatively, ‘F’ can be set for Fortran-style (column-major) order.

Here’s an example of using the zeros() function to create arrays of zeros:

13 (1)
Explanation:

In the Example, we incorporate the NumPy library using import numpy as np. The zeros() function steps in to craft two arrays:

arr_1d and arr_2d.

  • arr_1d emerges as a one-dimensional array housing 5 elements, all initialized as zeros.
  • arr_2d emerges as a two-dimensional array adopting the shape (3, 4), translating to 3 rows and 4 columns, all populated with zeros.

To inspect the arrays, we enlist the print() function to exhibit their content. The outcome surfaces as arrays brimming with zeros. This function proves instrumental when a preliminary array of zeros is indispensable for computations or data storage. It boasts widespread utility across scientific, numerical, and machine learning landscapes.

Creating a NumPy Array or Ones:

In the realm of NumPy, the ones() function serves the purpose of fabricating arrays enriched with ones. This versatile function enables the specification of the array’s shape and data type. The outcome takes the form of an array initialized with ones across all its elements.

The ones() function syntax is as follows: 

numpy.ones(shape, dtype=float, order=’C’)

Let’s delve into the distinct parameters of the ones() function:

  • shape (required): Defines the resulting array’s structure. It can be an integer indicating elements in a one-dimensional array or a tuple of integers denoting multi-dimensional array dimensions.
  • dtype (optional): Dictates the data type of elements in the resultant array. Default is float, with other common types like int (integer) and bool (boolean).
  • order (optional): Determines the array’s memory layout. Default is ‘C’, reflecting C-style (row-major) order. Alternatively, ‘F’ can be employed for Fortran-style (column-major) order.

Here’s an example of using the ones() function to create arrays of ones:

14

In the above example, we import the NumPy library using import numpy as np.

We use the ones() function to create two arrays: arr_1d and arr_2d.

  • arr_1d is a one-dimensional array with 5 elements. It will be initialized with ones.
  • arr_2d is a two-dimensional array with shape (3, 4), meaning it has 3 rows and 4 columns. All elements in this array will be ones.

The ones() function is useful when you need to initialize an array with ones before performing computations or storing data.

The Bottom Line

In this second segment of our NumPy exploration, we’ve dived into the realm of multi-dimensional arrays, mastering the art of crafting arrays with diverse values. The linspace(), zeros(), and ones() functions have unveiled versatile approaches to data manipulation, providing us the tools to tailor arrays to our precise needs. As we harness these capabilities, we pave the way for enhanced numerical computations, scientific endeavors, and data analysis tasks. Stay tuned for the next installment, where we’ll continue our journey into the depths of NumPy’s dynamic functionalities. If you enjoyed the blog follow 1stepgrow.