How to Create ndarrays in NumPy: A Comprehensive Guide

NumPy, an abbreviation for Numerical Python, stands as a cornerstone package for numerical computation within Python. Central to its functionality lies the ndarray (n-dimensional array) object, facilitating streamlined manipulation of extensive datasets. This guide delves into diverse techniques for creating ndarrays in NumPy, ranging from basic conversions to advanced array generation functions.

1. Converting Sequences to ndarrays.

The most straightforward way to create an ndarray in NumPy is by using the `np.array()` function. This function accepts any sequence-like object and produces a new NumPy array containing the passed data.

1.1 Example1.

Below is this example source Code.

import numpy as np

def create_ndarray_example1():
    # Example 1: Converting a list to an array
    data1 = [6, 7.5, 8, 0, 1]
    arr1 = np.array(data1)
    print(arr1)
    # Output: array([6. , 7.5, 8. , 0. , 1. ])

    # Example 2: Converting a nested list to a multidimensional array
    data2 = [[1, 2, 3, 4], [5, 6, 7, 8]]
    arr2 = np.array(data2)
    print(arr2)
    # Output:
    # array([[1, 2, 3, 4],
    #        [5, 6, 7, 8]])


if __name__ == "__main__":
    create_ndarray_example1()

Output.

[6.  7.5 8.  0.  1. ]
[[1 2 3 4]
 [5 6 7 8]]

1.2 Example2.

Source Code.

import numpy as np

def create_ndarray_example2():
    # Converting a tuple to an array
    data3 = (9, 10, 11, 12)
    arr3 = np.array(data3)
    print(arr3)
    # Output: array([ 9, 10, 11, 12])

    # Converting a list of strings to an array
    data4 = ['apple', 'banana', 'cherry']
    arr4 = np.array(data4)
    print(arr4)
    # Output: array(['apple', 'banana', 'cherry'], dtype='<U6')


if __name__ == "__main__":
    create_ndarray_example2()

Output.

[ 9 10 11 12]
['apple' 'banana' 'cherry']

2. Array Creation Functions.

In addition to `np.array()`, NumPy provides several functions for creating new arrays with specific properties. Let’s explore some of these functions:

2.1 numpy.zeros and numpy.ones.

These functions create arrays filled with zeros or ones, respectively, with a given length or shape.

import numpy as np

def create_ndarray_example3():
    # Creating an array of zeros with a specified shape
    zeros_arr = np.zeros((3, 4))
    print(zeros_arr)
    # Output:
    # array([[0., 0., 0., 0.],
    #        [0., 0., 0., 0.],
    #        [0., 0., 0., 0.]])

    # Creating an array of ones with a specified shape
    ones_arr = np.ones((2, 3, 2))
    print(ones_arr)
    # Output:
    # array([[[1., 1.],
    #         [1., 1.],
    #         [1., 1.]],
    #        [[1., 1.],
    #         [1., 1.],
    #         [1., 1.]]])

   
if __name__ == "__main__":
   create_ndarray_example3()

Output.

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

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

2.2 numpy.empty and numpy.arange.

2.2.1 Example.

Example code.

import numpy as np
    
def create_ndarray_example4():
    # Creating an uninitialized array with a specified shape
    empty_arr = np.empty((2, 3))
    print(empty_arr)
    # Output:
    # array([[1.72723371e-077, 0.00000000e+000, 2.47032823e-323],
    #        [0.00000000e+000, 0.00000000e+000, 0.00000000e+000]])

    # Creating an array with a range of values
    range_arr = np.arange(10)
    print(range_arr)
    # Output: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

if __name__ == "__main__":
    create_ndarray_example4()

Output.

[[-1.28822975e-231  1.49457760e-154  1.48219694e-323]
 [ 3.95252517e-323  1.18575755e-322  4.17201348e-309]]
[0 1 2 3 4 5 6 7 8 9]

In NumPy, `np.empty` and `np.arange` are two functions used for creating ndarrays. While they serve different purposes, both are valuable tools in array manipulation and numerical computing.

2.2.2 np.empty(shape, dtype=float, order=’C’).

The `np.empty` function creates an uninitialized array of specified shape and data type. Unlike `np.zeros`, which initializes the array elements to zeros, or `np.ones`, which initializes them to ones, `np.empty` does not set the values of the array elements. Instead, it allocates memory for the array without initializing the values, which can lead to unpredictable initial values in the array.

In this example, `np.empty` creates a 2×3 array without initializing its values. As a result, the array contains arbitrary values that were present in the memory at the time of allocation. It’s essential to initialize the array explicitly if you intend to use all its elements.

2.2.3 np.arange([start, ]stop, [step, ], dtype=None).

The `np.arange` function returns an array with evenly spaced values within a given range. It is similar to Python’s built-in `range` function but returns an ndarray instead of a list.

In this example, `np.arange(10)` generates an array containing values from 0 to 9 (inclusive), with a step size of 1. You can also specify the start, stop, and step arguments to define a custom range of values. Here, `np.arange(1, 10, 2)` generates an array containing odd numbers from 1 to 9.

import numpy as np

def create_ndarray_example5():
    # Example:
    custom_range_arr = np.arange(1, 10, 2)
    print(custom_range_arr)
    # Output: array([1, 3, 5, 7, 9])

if __name__ == "__main__":
    create_ndarray_example5()

3. Conclusion.

These are just a few examples of the array creation functions available in NumPy. By leveraging these functions, you can efficiently generate ndarrays tailored to your specific needs. Experiment with different shapes, data types, and values to unlock the full potential of NumPy arrays in your numerical computations.

4. Video Demo For This Article.

You can watch the video of this example article below.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.