Using numpy.asarray() Function

The NumPy asarray() function is used to convert the given input to an array. The input data can be in the form of a list, tuple, scalar, string, or set. The data type of the array is inferred from the input data.

Key Difference: Both numpy.array() and numpy.asarray() are used to create or convert data into a NumPy array. The key difference is that numpy.array() creates a copy of the object (changes won't reflect in the original), whereas numpy.asarray() will not create a copy if the input is already an ndarray (so changes would reflect).
numpy.asarray(arr, dtype=None, order=None, device=None, copy=None, like=None)

Parameters

  • arr: This is the required input parameter. It can be any array-like object or any nested sequences. If object is a scalar, a 0-dimensional array containing object is returned.
  • dtype: Specifies the desired data type of the array elements (e.g., int, float, complex, str). If not specified, NumPy automatically considers the data type based on the input object.
  • copy (optional): If True, a new copy of the object is always created. If False, the function tries to avoid copying the data and just creates a view.
  • device (optional): The device on which to place the created array. Default is None.
  • like (optional): Allows creation of an array which is like the input object but uses an existing array-like object.
  • order (optional): Specifies the memory layout ('C', 'F', 'A', 'K').

Return Value

Returns a NumPy array with the same data type as the input data, unless explicitly specified using the dtype parameter.

Example: Basic Conversion

import numpy as np my_array = np.asarray([1, 2, 3, 4]) print("Array :", my_array)

Output:

Numpy Array : [1 2 3 4]

Example: Creating an array using Sequences (Tuple)

A NumPy array can be created using sequences such as lists, tuples, or sets by passing them as arguments to the function.

import numpy as np my_tuple = (5, 10, 15, 20) print(type(my_tuple)) my_array = np.asarray(my_tuple) print("Numpy Array :", my_array) print(type(my_array))

Output:

<class 'tuple'> Numpy Array : [ 5 10 15 20] <class 'numpy.ndarray'>

Example: Creating n Dimension array

The numpy.asarray() function can create an N-dimensional array by passing multiple sequences (like lists) of the same size. If sizes differ, it raises a ValueError.

import numpy as np my_array = np.asarray([[10, 20, 30, 40], [11, 22, 33, 44]]) print("Numpy 2D Array :") print(my_array)

Output:

Numpy 2D Array : [[10 20 30 40] [11 22 33 44]]

Example: numpy.array() Vs numpy.asarray()

In numpy.asarray(), any changes made to the resulting array will be reflected in the original array if the input is already a NumPy array (as it does not create a copy). In numpy.array(), changes made to the new array will not affect the original array.

import numpy as np # creating array Original_Array = np.array([2, 3, 4, 5, 6]) print("Original array : ", Original_Array) # assigning value to np.array np_array = np.array(Original_Array) # assigning value to np.asarray np_asarray_array = np.asarray(Original_Array) Original_Array[3] = 0 print("np.array Array : ", np_array) >>> Original_Array array([2, 3, 4, 0, 6]) >>> np_array array([2, 3, 4, 5, 6]) >>> np_asarray_array array([2, 3, 4, 0, 6])

Using numpy.asanyarray() Function

The NumPy asanyarray() function is used to convert the input to an array, but keeps ndarray subclasses unchanged. This means if the input data is not an array, it will convert it into a standard numpy array. If the input is already a NumPy ndarray subclass (e.g., numpy.matrix or other custom subclasses), it is returned as is without converting it to a plain ndarray.

Apart from array, following are other input values to the numpy.asanyarray() function:

  • Scalars - It can be any numeric value. For example: 3.4, 5, 112.
  • Sequences - It can be list, tuple datatypes. For example: [1,2,3,4], ('a', 'b', 'c', 'd').
  • Nested Sequences - It can be nested tuples or lists. For example: [[1,2,3], [4,5,6]].
numpy.asanyarray(arr, dtype=None, order=None, like=None)

Parameters

  • arr: This is the required input parameter. It can be any array-like object (like a list, tuple, or another NumPy array) that we want to convert into a NumPy array.
  • dtype (optional): It specifies the desired data type of the array elements (e.g., int, float, complex, str). If not specified, NumPy will automatically consider the data type based on the input object.
  • like (optional): It allows the creation of an array which is like the input object but uses an existing array-like object (like another NumPy array).
  • order (optional): It specifies the memory layout of the array ('C', 'F', 'A', 'K').

Return Value

This function returns ndarray. If the input data is an ndarray or a subclass of ndarray, it is returned as-is and no copy is performed.

Example: Basic Conversion

import numpy as np my_Array = np.asanyarray([1, 2, 3, 4, 5]) print("Numpy Array:", my_Array) print(type(my_Array))

Output:

Numpy Array: [1 2 3 4 5] <class 'numpy.ndarray'>

Example: Creating an Array Using Sequences

A NumPy array can be created using sequences such as lists, tuples, or sets by passing them as arguments to the numpy.asanyarray() function.

import numpy as np # defined tuple my_tuple = (15, 25, 35, 45) my_Array = np.asanyarray(my_tuple) print("Numpy Array:", my_Array) print(type(my_Array))

Output:

Numpy Array: [15 25 35 45] <class 'numpy.ndarray'>

Example: Converting Scalar to Array

Using numpy.asanyarray() function is used to convert scalar value to a numpy array.

import numpy as np # initalizing a scalar value my_scalar = 100 print("Input scalar : ", my_scalar) out_arr = np.asanyarray(my_scalar) print("output array from input scalar : ", out_arr) print(type(out_arr))

Output:

Input scalar : 100 output array from input scalar : 100 <class 'numpy.ndarray'>

Example: Creating n Dimensional Array

We can create an n-dimensional NumPy array by passing nested sequences such as nested list (list of lists) or nested tuple. However, if the nested sequences have unequal sizes, a ValueError will be raised.

import numpy as np my_list = [[1, 2, 3], [10, 20, 30], [100, 200, 300]] out_arr = np.asanyarray(my_list) print("2D Numpy Array - ") print(out_arr)

Output:

2D Numpy Array - [[ 1 2 3] [ 10 20 30] [100 200 300]]

Example: Passing an Array as an Argument

When a standard NumPy array is passed as an argument to the numpy.asanyarray() function, it remains unchanged. However, if a subclass of numpy.ndarray (like numpy.matrix) is passed, it is returned as it is, preserving the subclass type.

import numpy as np # Input: NumPy matrix (a subclass of ndarray) mat = np.matrix([[1, 2], [3, 4]]) arr1 = np.asanyarray(mat) print(type(arr1)) # Input: Standard ndarray arr = np.array([5, 6, 7]) arr2 = np.asanyarray(arr) print(type(arr2))

Output:

<class 'numpy.matrix'> <class 'numpy.ndarray'>

Using numpy.copy() Function

The NumPy copy() function is used to copy a given object into an array. The object can be a tuple, list, nested list, nested tuple, or an array.

Assignment (=) vs numpy.copy()
We can create an array using the assignment (=) operator. However, the assignment operator creates a reference to the original array, meaning both variables point to the same memory location. Therefore, if changes are made to one array, they will be reflected in the other.

On the other hand, when we create a NumPy array using numpy.copy(), it creates a new, separate copy of the array. As a result, changes made to one array will not affect the other.

Note: The numpy.array(arr, copy=True) function is similar to the numpy.copy() function, as both generate a new array that duplicates the data from the original, ensuring any modifications to the new array do not affect the original.

numpy.copy(array, order='K', subok=False)

Parameters

  • array: The array that is to be copied.
  • order (optional): This specifies the order in which the elements are filled in the copied class ('C', 'F', 'A', 'K').
  • subok (optional): It determines whether to subclass the output array if the data type is changed or to return a base-class array.

Return Value

This function returns the array interpretation of the given input.

Example: Basic Conversion

Following is a basic example to create a NumPy array using the numpy.copy() function.

import numpy as np # creating an array (list) my_array = [24, 9, 1, 8, 97] # implementing the numpy.copy() function copy_Array = np.copy(my_array) print("Numpy Array:", copy_Array) print(type(copy_Array))

Output:

Numpy Array: [24 9 1 8 97] <class 'numpy.ndarray'>

Example: Copy Numpy Array into Another Array

We can copy a NumPy array into another array. Here, we copy my_array into copy_Array.

import numpy as np # creating an array my_array = np.array([10, 99, 56, 34, 78]) print("Original Array", my_array) print(type(my_array)) # implementing the numpy.copy() function copy_Array = np.copy(my_array) print("Numpy Array:", copy_Array) print(type(copy_Array))

Output:

Original Array [10 99 56 34 78] <class 'numpy.ndarray'> Numpy Array: [10 99 56 34 78] <class 'numpy.ndarray'>

Example: Create Array with '=' and numpy.copy()

The assignment operator creates a reference to the same array, while numpy.copy() creates a separate copy, so changes to one array do not affect the other.

import numpy as np # create an array my_Array = np.array([10, 45, 78, 15, 99]) print("Original Numpy Array -", my_Array) # copy an array using assignment operator my_Array1 = my_Array # copy an array using np.copy() my_Array2 = np.copy(my_Array) # change 1st element of new array my_Array1[0] = 88 # print both arrays print("Numpy Array copied using assignment operator -", my_Array1) print("Numpy Array copied using copy() operator -", my_Array2)

Output:

Original Numpy Array - [10 45 78 15 99] Numpy Array copied using assignment operator - [88 45 78 15 99] Numpy Array copied using copy() operator - [10 45 78 15 99]

Key Difference Summary

Function If input is already NumPy array Creates copy? Main purpose
np.array() Usually creates a new array Yes by default Create an array
np.asarray() Returns same array No Convert to ndarray without unnecessary copy
np.asanyarray() Returns same array No Like asarray(), but preserves subclasses
arr.copy() / np.copy() Creates independent array Yes Explicitly make a copy