A detailed guide to numpy.array() function (7 examples)

Updated: February 29, 2024 By: Guest Contributor Post a comment

Introduction

NumPy is a core library for numerical computing in Python. It provides a high-performance multidimensional array object and tools for working with these arrays. One of the fundamental functions in NumPy is numpy.array(), which is used to create array objects. This guide delves into the numpy.array() function with seven practical examples to showcase its versatility and power.

Prerequisites

  • A basic understanding of Python programming.
  • NumPy installed in your working environment. You can install NumPy using the command pip install numpy.

Syntax & Parameters

Syntax:

numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)

Parameters:

  • object: array_like. An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence.
  • dtype: data-type, optional. The desired data type for the array. If not specified, the type will be determined as the minimum type required to hold the objects in the sequence.
  • copy: bool, optional. If True (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.).
  • order: {‘K’, ‘A’, ‘C’, ‘F’}, optional. Specifies the memory layout of the array. ‘C’ means C-order, ‘F’ means Fortran-order, ‘A’ means ‘F’ if the object is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the input order as closely as possible.
  • subok: bool, optional. If True, then subclasses will be passed through; otherwise, the returned array will be forced to be a base-class array (default is False).
  • ndmin: int, optional. Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape of the array to meet this requirement.

Returns:

  • out: ndarray. An array object satisfying the specified requirements.

Example 1: Basic Array Creation

Let’s start with the most basic usage of numpy.array() to create a simple array from a Python list.

import numpy as np

# Creating a simple array
simple_array = np.array([1, 2, 3, 4, 5])
print(simple_array)
# Output: [1 2 3 4 5]

Example 2: Specifying Data Type

numpy.array() allows you to specify the data type of the array using the dtype parameter. This is useful for optimizing memory usage and computational efficiency.

import numpy as np

# Creating an array with a specific data type
int_array = np.array([1, 2, 3, 4], dtype=np.int32)
print(int_array)
# Output: [1 2 3 4]

Example 3: Multidimensional Arrays

NumPy shines when working with multidimensional arrays. The numpy.array() function can easily create arrays with multiple dimensions.

import numpy as np

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

Example 4: Arrays of Zeros and Ones

Beyond creating arrays from existing data, numpy.array() can also be used to create arrays filled with zeros or ones, which is common in various numerical computing applications.

import numpy as np

# Creating an array of zeros
zeros_array = np.zeros((2, 3))
print(zeros_array)
# Output:
# [[0. 0. 0.]
#  [0. 0. 0.]]

# Creating an array of ones
ones_array = np.ones((3, 4))
print(ones_array)
# Output:
# [[1. 1. 1. 1.]
#  [1. 1. 1. 1.]
#  [1. 1. 1. 1.]]

Example 5: Using the copy Flag

When you create an array using numpy.array(), you have the option to make a deep copy of the original data by setting the copy flag to True. This ensures that changes to the newly created array don’t affect the original data.

import numpy as np

# Creating an array with the copy flag
original = [1, 2, 3]
new_array with the computer to resume actively monitoring the environment. re assign notifications as = np.array(original, copy=True)
original[0] = 10
print(new_array)
print(original)
# Output of new_array: [1 2 3]
# Output of original: [10, 2, 3]

Example 6: Nested Arrays and Shape Mismatch

When inputting lists with different lengths into numpy.array(), it’s important to note that NumPy expects uniform lengths to form a proper multidimensional array. A shape mismatch will result in an array of lists rather than a multidimensional array.

import numpy as np

# Demonstrating shape mismatch
mismatched_array = np.array([[1, 2], [3, 4, 5]])
print(mismatched_array)
# Output: [list([1, 2]) list([3, 4, 5])]

Example 7: Advanced Operations with Arrays

NumPy arrays support various advanced operations that are efficient and powerful. Let’s see an example of performing element-wise multiplication and summing all the elements.

import numpy as np

# Performing advanced operations
data = np.array([1, 2, 3, 4])
result = data * 2 + 6
sum_result = np.sum(result)
print("Modified data:", result)
print("Sum of modified data:", sum_result)
# Output:
# Modified data: [ 8 10 12 14]
# Sum of modified data: 44

Conclusion

The numpy.array() function is a versatile tool that serves as the foundation of array-based computing in NumPy. Through these examples, we’ve explored how it can be used for creating basic arrays, specifying data types, handling multidimensional data, and performing advanced computational tasks. With a deep understanding of numpy.array(), you’re now equipped to tackle an array of numerical computing challenges in Python.