How to compute the absolute values of a 2D array in Python
Overview
In Python, the absolute() method from the numpy module is used to find the absolute values of a NumPy array.
This method computes the absolute values of a complex array input. This is done element-wise.
Note: In Python, a list of lists can be used to generate a two-dimensional (2D) array.
Syntax
numpy.absolute(arr,out=None, where=True,casting='same_kind', order='K', dtype=None,subok=True[, signature, extobj])
-
<ufunc absolute'>)
Parameters
-
arr: This represents the input array. -
out: This specifies where the result is stored. This is an optional parameter. -
where: This represents the condition in which the input gets broadcasted. This is an optional parameter. -
casting: This specifies the kind of casting that is allowed. The value may beno,equiv,safe,same_kind, orunsafe. This is an optional parameter. -
order: This defines the output array’s memory layout and calculation iteration order. Its default value isK.Cindicates that the output should be C-contiguous.Findicates that it should be F-contiguous.Aindicates that it should be F-contiguous if the inputs are F-contiguous but not also C-contiguous. Otherwise, C-contiguous.Kindicates that it should closely match the element ordering of the inputs.
-
subok: IfFalseis specified, it returns a strict array rather than a subtype. The default isTrue. -
dtype: It modifies theDTypeof the output arrays. Its default value isNone.
Return value
This method returns absolute values of an array.
Note: This function is abbreviated as
np.abs.
Example
# import numpyimport numpy as np# create 2D array using np.arrayarr = np.array([[-7,-3.4,1.2 + 1j], [-2,3 + 1j,-9.5]])print('Abs Arr:', np.absolute(arr), sep='\n')print('Org Arr:', arr, sep='\n')print('Abs Arr:', np.absolute(arr, out=arr), sep='\n')print('Org Arr:', arr, sep='\n')
Explanation
- Line 5: We create a 2D array called
arrusing the list of lists, which is then passed as an argument to the methodnp.array()to convert it to a numpy array. - Line 7: We use the
np.absolute()method to calculate the absolute values of the input array,arr. - Line 10: We not only use the
np.absolute()method to calculate the absolute values of the input arrayarr, but also store the results in the same array.