Skip to content

Commit 349ee28

Browse files
[Edit]: NumPy .abs() (#6982)
* [Edit] SQL: DATEDIFF() * Update datediff.md * [Edit]: NumPy `.abs()` * Few Changes * Revert "Few Changes" This reverts commit 0e1db61. * Update content/numpy/concepts/math-methods/terms/abs/abs.md * Update content/numpy/concepts/math-methods/terms/abs/abs.md * Few changes * Update content/numpy/concepts/math-methods/terms/abs/abs.md * Update content/numpy/concepts/math-methods/terms/abs/abs.md ---------
1 parent a1f4d84 commit 349ee28

File tree

1 file changed

+101
-41
lines changed
  • content/numpy/concepts/math-methods/terms/abs

1 file changed

+101
-41
lines changed

content/numpy/concepts/math-methods/terms/abs/abs.md

Lines changed: 101 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -11,92 +11,152 @@ Tags:
1111
- 'NumPy'
1212
CatalogContent:
1313
- 'learn-python-3'
14-
- 'paths/computer-science'
1514
- 'paths/data-science'
16-
- 'paths/data-science-foundations'
1715
---
1816

19-
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.
17+
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.
2018

21-
> **Note:** `numpy.abs()` is identical to `numpy.absolute()`, and they can be used interchangeably.
19+
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.
20+
21+
> **Note:** `numpy.abs` is a shorthand alias for the `numpy.absolute()` function.
2222
2323
## Syntax
2424

2525
```pseudo
26-
numpy.abs(input_value, out=None, where=True)
26+
numpy.abs(x, out=None, where=True)
2727
```
2828

29-
or alternatively,
29+
**Parameters:**
3030

31-
```pseudo
32-
numpy.absolute(input_value, out=None, where=True)
33-
```
31+
- `x`: The input array or scalar value for which absolute values will be computed. Can be integer, float, or complex numbers.
32+
- `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.
33+
- `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.
3434

35-
- `input_value`: The input number or array for which the absolute value will be computed.
36-
- `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.
37-
- `where` (optional): A boolean array that determines which elements of the input array should have the absolute value function applied:
38-
- If the condition is `True` at a given position, the absolute value is computed for that element.
39-
- If the condition is `False`, the original value is retained.
40-
- If no value is provided, the absolute value is computed for every element.
35+
**Return value:**
4136

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

44-
This example demonstrates using `.abs()` function to calculate the absolute value of an array:
39+
## Example 1: Basic Array Operations using `.abs()` method
40+
41+
This example demonstrates the fundamental usage of `numpy.abs()` with different numeric data types:
4542

4643
```py
47-
# Importing the 'numpy' library as 'np'
4844
import numpy as np
4945

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

53-
# Computing the absolute value of the array
54-
arr = np.abs(arr)
50+
# Computing absolute values
51+
abs_integers = np.abs(integers)
52+
abs_floats = np.abs(floats)
5553

56-
print(arr)
54+
print("Original integers:", integers)
55+
print("Absolute integers:", abs_integers)
56+
print("Original floats:", floats)
57+
print("Absolute floats:", abs_floats)
5758
```
5859

59-
The above example code results in the following output:
60+
This example results in the following output:
6061

6162
```shell
62-
[1. 1.5 0. 3.]
63+
Original integers: [-5 -2 0 3 7]
64+
Absolute integers: [5 2 0 3 7]
65+
Original floats: [-3.14 -1.5 0. 2.71 8.9 ]
66+
Absolute floats: [3.14 1.5 0. 2.71 8.9 ]
6367
```
6468

65-
## Example 2
69+
The function preserves the original data type while converting negative values to positive, leaving zero and positive values unchanged.
70+
71+
## Example 2: Financial Data Analysis
6672

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

6975
```py
70-
# Importing the 'numpy' library as 'np'
7176
import numpy as np
7277

73-
# Creating a numpy array
74-
arr = np.array([-1, -2, -3, -4])
78+
# Stock price changes over a week (percentage changes)
79+
daily_returns = np.array([-2.3, 1.8, -0.5, 3.2, -1.1])
80+
portfolio_values = np.array([10000, 9770, 9946, 9896, 10213, 10101])
81+
82+
# Calculate absolute returns for risk analysis
83+
abs_returns = np.abs(daily_returns)
7584

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

79-
print(arr)
89+
print("Daily returns (%):", daily_returns)
90+
print("Absolute returns (%):", abs_returns)
91+
print("Average absolute return:", np.mean(abs_returns))
92+
93+
print("\nDaily portfolio changes ($):", daily_changes)
94+
print("Absolute changes ($):", abs_changes)
95+
print("Total volatility ($):", np.sum(abs_changes))
8096
```
8197

82-
The above example code results in the following output:
98+
This example results in the following output:
8399

84100
```shell
85-
[-1 -2 3 4]
101+
Daily returns (%): [-2.3 1.8 -0.5 3.2 -1.1]
102+
Absolute returns (%): [2.3 1.8 0.5 3.2 1.1]
103+
Average absolute return: 1.78
104+
105+
Daily portfolio changes ($): [-230 176 -50 317 -112]
106+
Absolute changes ($): [230 176 50 317 112]
107+
Total volatility ($): 885
86108
```
87109

88-
> **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.
110+
Financial analysts use absolute values to measure portfolio volatility and risk without caring about the direction of price movements, focusing only on magnitude.
89111

90-
## Codebyte Example
112+
## Codebyte Example: Signal Processing and Complex Numbers
91113

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

94116
```codebyte/python
95117
import numpy as np
96118
97-
arr = np.array([-1.2, -23, -101, -400, 20, -100, -99])
119+
# Simulating a complex signal (common in signal processing)
120+
time = np.linspace(0, 2*np.pi, 8)
121+
complex_signal = np.exp(1j * time) # Complex exponential signal
122+
123+
# Adding some noise with negative values
124+
noisy_data = np.array([1+2j, -3-4j, 0+5j, -2+1j, 4-3j])
98125
99-
np.abs(arr, out=arr, where=arr>-100)
126+
# Calculate magnitudes (absolute values)
127+
signal_magnitude = np.abs(complex_signal)
128+
data_magnitude = np.abs(noisy_data)
100129
101-
print(arr)
130+
print("Complex signal:", complex_signal)
131+
print("Signal magnitudes:", signal_magnitude)
132+
print("\nNoisy complex data:", noisy_data)
133+
print("Data magnitudes:", data_magnitude)
134+
135+
# Using where parameter for conditional processing
136+
filtered_magnitudes = np.abs(noisy_data, where=(np.real(noisy_data) > 0))
137+
print("\nFiltered magnitudes (positive real parts only):", filtered_magnitudes)
102138
```
139+
140+
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.
141+
142+
## Frequently Asked Questions
143+
144+
### 1. What's the difference between `numpy.abs()` and Python's built-in `abs()`?
145+
146+
`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.
147+
148+
### 2. Can I use `numpy.abs()` with multidimensional arrays?
149+
150+
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.
151+
152+
### 3. How does `numpy.abs()` handle special values like `Infinity` and `NaN`?
153+
154+
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.
155+
156+
### 4. Does `numpy.abs()` modify the original array?
157+
158+
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.
159+
160+
### 5. What happens when I use the `where` parameter?
161+
162+
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.

0 commit comments

Comments
 (0)