import pandas as pd
df = pd.DataFrame({'MATH': [-30, 40, -50], 'ENGLISH': [20, -30, 40]})
print(df.abs())
Expected Output:
MATH ENGLISH
0 30 20
1 40 30
2 50 40
The DataFrame.abs() method converts numeric values within a Pandas DataFrame or Series into non-negative magnitudes. It processes elements individually across integer, floating-point, and complex data types without altering index labels or column names.
DataFrame.abs() or Series.abs()Applying abs() to a single Series transforms negative quantities into positive numbers while preserving the original index order and series data type.
import pandas as pd
s = pd.Series([-1.5, 2.0, -3.75, 0.0, -42.0])
abs_s = s.abs()
print(abs_s)
Expected Output:
0 1.50
1 2.00
2 3.75
3 0.00
4 42.00
dtype: float64
When DataFrames contain string metadata alongside numerical columns, calling abs() across the entire object will trigger a TypeError. Use select_dtypes(include='number') to extract and transform numeric data cleanly.
import pandas as pd
student_data = {
'NAME': ['Ravi', 'Raju', 'Alex', 'Ananya'],
'MATH_VARIANCE': [-12.5, 8.0, -15.2, 0.0],
'ENG_VARIANCE': [5.0, -10.0, 14.0, -3.5]
}
df = pd.DataFrame(student_data)
# Transform numeric columns while preserving text metadata
df[['MATH_ABS', 'ENG_ABS']] = df[['MATH_VARIANCE', 'ENG_VARIANCE']].abs()
print(df)
The abs() method preserves missing NaN entries. For complex numbers of the form $a + bi$, abs() calculates the magnitude $\sqrt{a^2 + b^2}$.
import pandas as pd
import numpy as np
df_complex = pd.DataFrame({
'REAL': [-10.5, np.nan, -25.0],
'COMPLEX': [3 + 4j, -5 - 12j, np.nan]
})
print(df_complex.abs())
Expected Output:
REAL COMPLEX
0 10.5 5.0
1 NaN 13.0
2 25.0 NaN
Calculating Mean Absolute Error (MAE) between target benchmarks and actual observed figures is a fundamental forecasting application.
import pandas as pd
actual = pd.Series([46500, 78200, 54000, 91500])
target = pd.Series([50000, 75000, 60000, 90000])
mae = (actual - target).abs().mean()
print(f"Mean Absolute Error: ${mae:.2f}")
Q: Does abs() perform modifications in-place?
No, abs() creates and returns a new DataFrame or Series object. Assign the output back to overwrite existing variables.
Q: Can abs() process mixed text columns directly?
No, string values raise a TypeError. Select numeric columns using select_dtypes(include='number') before running abs().
abs() to non-numeric columns.df[['col1', 'col2']].abs().
Explore interactive code cells, dynamically generate classes, test type vs isinstance comparisons, and run self-validating assertions.
View on GitHubAuthor & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.