0
0
NumPydata~5 mins

np.abs() for absolute values in NumPy

Choose your learning style9 modes available
Introduction

We use np.abs() to find how far numbers are from zero, ignoring if they are positive or negative.

When you want to measure distance or size without caring about direction.
When calculating errors or differences where only the amount matters.
When working with data that can have negative values but you need positive results.
When preparing data for graphs that show magnitude only.
When comparing values regardless of sign.
Syntax
NumPy
np.abs(x)

x can be a single number, list, or array.

The function returns the absolute value(s) of x.

Examples
Returns 5 because the absolute value of -5 is 5.
NumPy
np.abs(-5)
Returns an array with all positive values: [1 2 3 4].
NumPy
np.abs([1, -2, 3, -4])
Works with numpy arrays and returns [1.5 2.3 3.7].
NumPy
np.abs(np.array([-1.5, 2.3, -3.7]))
Sample Program

This program creates a numpy array with positive and negative numbers. Then it uses np.abs() to get their absolute values and prints the result.

NumPy
import numpy as np

numbers = np.array([-10, 0, 5, -3.5, 2])
absolute_values = np.abs(numbers)
print(absolute_values)
OutputSuccess
Important Notes

np.abs() works element-wise on arrays, so it returns an array of absolute values.

It works with integers, floats, and complex numbers (returns magnitude for complex).

Summary

np.abs() gives the size of numbers without their sign.

It works on single numbers and arrays alike.

Useful for measuring distances, errors, or magnitudes.