Python | Numpy MaskedArray.__abs__

Python | Numpy MaskedArray.__abs__

The numpy.ma.MaskedArray.__abs__ method in NumPy's masked array module computes the element-wise absolute values of the data in the MaskedArray.

MaskedArray is a subclass of numpy.ndarray that has a separate mask indicating which entries are "missing" or "invalid." When you perform operations on a MaskedArray, the computations will ignore these masked elements.

Here's a simple example to illustrate the use of __abs__ with a MaskedArray:

import numpy as np import numpy.ma as ma # Create a MaskedArray data = np.array([1, -2, 3, -4, 5]) mask = [0, 0, 0, 1, 0] # Masking the 4th element (-4) masked_array = ma.array(data, mask=mask) print("Original MaskedArray:", masked_array) # Compute the absolute values absolute_values = masked_array.__abs__() print("Absolute values:", absolute_values) 

Output:

Original MaskedArray: [1 -2 3 -- 5] Absolute values: [1 2 3 -- 5] 

In the output, you can observe that the absolute values are computed for all the unmasked elements. The masked element (-- representing -4) remains unchanged.

Note: In practice, you wouldn't typically call the __abs__ method directly. Instead, you'd simply use Python's built-in abs() function or the numpy.abs() function:

absolute_values = abs(masked_array) 

or

absolute_values = np.abs(masked_array) 

Both of these will produce the same result.


More Tags

azure-devops-rest-api ngoninit special-characters shared web-config imageurl redis-commands database-schema hashtable webservice-client

More Programming Guides

Other Guides

More Programming Examples