Skip to content

[Edit]: NumPy .abs() #6982

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 22 commits into from
Jun 12, 2025
Merged
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
d0dd9bd
[Edit] SQL: DATEDIFF()
mamtawardhani May 21, 2025
9f5c19b
Update datediff.md
mamtawardhani May 21, 2025
c32e9f3
Merge branch 'Codecademy:main' into main
mamtawardhani May 23, 2025
4170ba2
Merge branch 'Codecademy:main' into main
mamtawardhani May 23, 2025
8325585
Merge branch 'Codecademy:main' into main
mamtawardhani May 26, 2025
8f6f8e8
Merge branch 'Codecademy:main' into main
mamtawardhani May 27, 2025
e4c54e8
Merge branch 'Codecademy:main' into main
mamtawardhani May 28, 2025
7b3b9c0
Merge branch 'Codecademy:main' into main
mamtawardhani May 29, 2025
27ecefd
Merge branch 'Codecademy:main' into main
mamtawardhani May 29, 2025
0392da4
Merge branch 'Codecademy:main' into main
mamtawardhani May 30, 2025
d550fa7
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 2, 2025
793be7d
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 3, 2025
2f03b61
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 3, 2025
57810db
[Edit]: NumPy `.abs()`
mamtawardhani Jun 3, 2025
0e1db61
Few Changes
avdhoottt Jun 12, 2025
8de3ada
Revert "Few Changes"
avdhoottt Jun 12, 2025
07e9280
Update content/numpy/concepts/math-methods/terms/abs/abs.md
avdhoottt Jun 12, 2025
cc41b6e
Update content/numpy/concepts/math-methods/terms/abs/abs.md
avdhoottt Jun 12, 2025
a9365cc
Few changes
avdhoottt Jun 12, 2025
ad5896f
Update content/numpy/concepts/math-methods/terms/abs/abs.md
avdhoottt Jun 12, 2025
8912a0e
Update content/numpy/concepts/math-methods/terms/abs/abs.md
avdhoottt Jun 12, 2025
9cea3f3
Merge branch 'main' into abs-numpy
avdhoottt Jun 12, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 101 additions & 41 deletions content/numpy/concepts/math-methods/terms/abs/abs.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,92 +11,152 @@ Tags:
- 'NumPy'
CatalogContent:
- 'learn-python-3'
- 'paths/computer-science'
- 'paths/data-science'
- 'paths/data-science-foundations'
---

In NumPy, the **`.abs()`** function calculates the absolute value of a given number or each element in an array. The absolute value of a number is its non-negative value or the number's distance from zero. This function can be applied to both real and complex numbers.
The NumPy's **`.abs()`** function calculates the absolute value of a given number or each element in an array. A number's absolute value is its non-negative value or its distance from zero. This function can be applied to both real and complex numbers.

> **Note:** `numpy.abs()` is identical to `numpy.absolute()`, and they can be used interchangeably.
NumPy's `.abs()` function is widely used in data science applications for cleaning datasets with negative values, calculating distances in machine learning algorithms, processing signal data, financial analysis for computing returns and losses, and scientific computing where absolute differences are required. The function works seamlessly with both real and complex numbers, making it versatile for various mathematical operations.

> **Note:** `numpy.abs` is a shorthand alias for the `numpy.absolute()` function.

## Syntax

```pseudo
numpy.abs(input_value, out=None, where=True)
numpy.abs(x, out=None, where=True)
```

or alternatively,
**Parameters:**

```pseudo
numpy.absolute(input_value, out=None, where=True)
```
- `x`: The input array or scalar value for which absolute values will be computed. Can be integer, float, or complex numbers.
- `out` (Optional): A location where the result will be stored. If `None` (default), a new array is returned. The inputs must have a shape that they broadcast to.
- `where` (Optional): A boolean array that determines which elements should have the absolute value function applied. Elements where the condition is `True` get computed, while `False` elements retain their original values. The default is `True` for all elements.

- `input_value`: The input number or array for which the absolute value will be computed.
- `out` (optional): A location where the result of the absolute value will be stored. If no value is provided, the default value of `None` is used and a new array is returned.
- `where` (optional): A boolean array that determines which elements of the input array should have the absolute value function applied:
- If the condition is `True` at a given position, the absolute value is computed for that element.
- If the condition is `False`, the original value is retained.
- If no value is provided, the absolute value is computed for every element.
**Return value:**

## Example 1
An array containing the absolute value of each element in the input. For complex numbers, returns the magnitude calculated as `√(real² + imaginary²)`.

This example demonstrates using `.abs()` function to calculate the absolute value of an array:
## Example 1: Basic Array Operations using `.abs()` method

This example demonstrates the fundamental usage of `numpy.abs()` with different numeric data types:

```py
# Importing the 'numpy' library as 'np'
import numpy as np

# Creating a numpy array
arr = np.array([1, -1.5, 0, -3])
# Creating arrays with mixed positive and negative values
integers = np.array([-5, -2, 0, 3, 7])
floats = np.array([-3.14, -1.5, 0.0, 2.71, 8.9])

# Computing the absolute value of the array
arr = np.abs(arr)
# Computing absolute values
abs_integers = np.abs(integers)
abs_floats = np.abs(floats)

print(arr)
print("Original integers:", integers)
print("Absolute integers:", abs_integers)
print("Original floats:", floats)
print("Absolute floats:", abs_floats)
```

The above example code results in the following output:
This example results in the following output:

```shell
[1. 1.5 0. 3.]
Original integers: [-5 -2 0 3 7]
Absolute integers: [5 2 0 3 7]
Original floats: [-3.14 -1.5 0. 2.71 8.9 ]
Absolute floats: [3.14 1.5 0. 2.71 8.9 ]
```

## Example 2
The function preserves the original data type while converting negative values to positive, leaving zero and positive values unchanged.

## Example 2: Financial Data Analysis

This example shows how the `where` parameter of `.abs()` function is used to specify which elements of the array undergo the absolute value function:
This example shows how `numpy.abs()` is used in financial analysis to calculate absolute returns and risk metrics:

```py
# Importing the 'numpy' library as 'np'
import numpy as np

# Creating a numpy array
arr = np.array([-1, -2, -3, -4])
# Stock price changes over a week (percentage changes)
daily_returns = np.array([-2.3, 1.8, -0.5, 3.2, -1.1])
portfolio_values = np.array([10000, 9770, 9946, 9896, 10213, 10101])

# Calculate absolute returns for risk analysis
abs_returns = np.abs(daily_returns)

# Computing the absolute value of only the elements that are less than -2
np.abs(arr, out=arr, where=arr<-2)
# Calculate daily value changes
daily_changes = np.diff(portfolio_values)
abs_changes = np.abs(daily_changes)

print(arr)
print("Daily returns (%):", daily_returns)
print("Absolute returns (%):", abs_returns)
print("Average absolute return:", np.mean(abs_returns))

print("\nDaily portfolio changes ($):", daily_changes)
print("Absolute changes ($):", abs_changes)
print("Total volatility ($):", np.sum(abs_changes))
```

The above example code results in the following output:
This example results in the following output:

```shell
[-1 -2 3 4]
Daily returns (%): [-2.3 1.8 -0.5 3.2 -1.1]
Absolute returns (%): [2.3 1.8 0.5 3.2 1.1]
Average absolute return: 1.78

Daily portfolio changes ($): [-230 176 -50 317 -112]
Absolute changes ($): [230 176 50 317 112]
Total volatility ($): 885
```

> **Note:** The `where` array must be broadcastable to the shape of the input array. Additionally, when using the `where` parameter, it is recommended to use the `out` parameter to specify where the result should be stored, which helps avoid errors with uninitialized memory.
Financial analysts use absolute values to measure portfolio volatility and risk without caring about the direction of price movements, focusing only on magnitude.

## Codebyte Example
## Codebyte Example: Signal Processing and Complex Numbers

In this codebyte example, the `.abs()` method computes the absolute value of the elements in the array that are greater than `-100`:
This example demonstrates how `numpy.abs()` handles complex numbers for signal processing applications:

```codebyte/python
import numpy as np

arr = np.array([-1.2, -23, -101, -400, 20, -100, -99])
# Simulating a complex signal (common in signal processing)
time = np.linspace(0, 2*np.pi, 8)
complex_signal = np.exp(1j * time) # Complex exponential signal

# Adding some noise with negative values
noisy_data = np.array([1+2j, -3-4j, 0+5j, -2+1j, 4-3j])

np.abs(arr, out=arr, where=arr>-100)
# Calculate magnitudes (absolute values)
signal_magnitude = np.abs(complex_signal)
data_magnitude = np.abs(noisy_data)

print(arr)
print("Complex signal:", complex_signal)
print("Signal magnitudes:", signal_magnitude)
print("\nNoisy complex data:", noisy_data)
print("Data magnitudes:", data_magnitude)

# Using where parameter for conditional processing
filtered_magnitudes = np.abs(noisy_data, where=(np.real(noisy_data) > 0))
print("\nFiltered magnitudes (positive real parts only):", filtered_magnitudes)
```

For complex numbers, `numpy.abs()` computes the magnitude using the formula `√(real² + imaginary²)`, which is crucial in signal processing for analyzing frequency components and signal strength.

## Frequently Asked Questions

### 1. What's the difference between `numpy.abs()` and Python's built-in `abs()`?

`numpy.abs()` is optimized for arrays and performs element-wise operations on entire arrays efficiently, while Python's built-in `abs()` works on individual numbers. For single values, both produce the same result, but `numpy.abs()` is much faster for array operations.

### 2. Can I use `numpy.abs()` with multidimensional arrays?

Yes, `numpy.abs()` works with arrays of any dimension. It applies the absolute value operation element-wise across all dimensions, preserving the original array shape.

### 3. How does `numpy.abs()` handle special values like `Infinity` and `NaN`?

The function returns positive infinity for both positive and negative infinity inputs. For NaN (Not a Number) values, it returns NaN, maintaining the invalid state of the computation.

### 4. Does `numpy.abs()` modify the original array?

No, `numpy.abs()` returns a new array with the absolute values. The original array remains unchanged unless you explicitly assign the result back to the original variable.

### 5. What happens when I use the `where` parameter?

The `where` parameter allows selective application of the absolute value function. Elements where the condition is `True` get their absolute value computed, while `False` elements retain their original values. If the `out` parameter is used, unmodified elements keep their existing values in the output array.