0
0
NumPydata~10 mins

np.abs() for absolute values in NumPy - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - np.abs() for absolute values
Input array or number
Call np.abs() function
Calculate absolute value element-wise
Return array or number with all values >= 0
np.abs() takes a number or array and returns the absolute value for each element, making all values non-negative.
Execution Sample
NumPy
import numpy as np
arr = np.array([-3, 0, 4, -7])
result = np.abs(arr)
print(result)
This code finds the absolute values of each element in the array.
Execution Table
StepInput Valuenp.abs() CalculationOutput Value
1-3abs(-3) = 33
20abs(0) = 00
34abs(4) = 44
4-7abs(-7) = 77
5All elements processedReturn array[3, 0, 4, 7]
💡 All elements processed, output array contains only non-negative values.
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
arr[-3, 0, 4, -7][-3, 0, 4, -7][-3, 0, 4, -7][-3, 0, 4, -7][-3, 0, 4, -7][-3, 0, 4, -7]
resultN/A[3, _, _, _][3, 0, _, _][3, 0, 4, _][3, 0, 4, 7][3, 0, 4, 7]
Key Moments - 3 Insights
Why does np.abs() return positive values even for negative inputs?
np.abs() calculates the distance from zero, which is always positive or zero, as shown in execution_table rows 1, 4.
Does np.abs() change the original array?
No, np.abs() returns a new array with absolute values, the original array stays the same as shown in variable_tracker for 'arr'.
Can np.abs() handle zero values?
Yes, zero stays zero because its absolute value is zero, as shown in execution_table row 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output value at step 3?
A0
B-4
C4
D7
💡 Hint
Check the 'Output Value' column at step 3 in the execution_table.
At which step does the condition 'abs(-7)' get calculated?
AStep 4
BStep 2
CStep 5
DStep 1
💡 Hint
Look for the input value '-7' in the execution_table under 'Input Value'.
If the input array was [5, -2, -8], what would be the output at step 2?
A-2
B2
C5
D-8
💡 Hint
np.abs() converts negative numbers to positive, see execution_table steps for reference.
Concept Snapshot
np.abs(x) returns the absolute value of x.
Works element-wise on arrays.
Negative values become positive.
Zero stays zero.
Original data is not changed.
Useful to measure distance or magnitude.
Full Transcript
This lesson shows how np.abs() works by taking an input array with negative and positive numbers. It calculates the absolute value for each element, turning negatives into positives and leaving zeros unchanged. The original array stays the same, and the output is a new array with all non-negative values. Step-by-step, each element is processed and converted. This helps understand how absolute values work in data science.