Pandas DataFrame transform() Method

import pandas as pd 

df = pd.DataFrame({'A': [1, 4], 'B': [9, 16]})
print(df.transform(lambda x: x ** 0.5))

Expected Output:

     A    B
0  1.0  3.0
1  2.0  4.0

1. Overview and Syntax

The DataFrame.transform() method applies functions across DataFrame axes to produce an object with identical index and column dimensions. Unlike apply() or agg(), transform() enforces that the output shape must strictly match the input shape.

Method Signature: DataFrame.transform(func, axis=0, *args, **kwargs)
Parameters:
• func: Function, string function name, list of functions, or dictionary mapping columns to functions.
• axis: 0 or 'index' (column-wise), 1 or 'columns' (row-wise).
Returns: A transformed DataFrame of identical shape.

2. Multi-Function Transformations

Pass a list of functions (e.g., NumPy or mathematical aliases) to compute multi-column transformed features.

import pandas as pd 
import numpy as np

df_vals = pd.DataFrame({'NUM': [1, 2, 3]})
print(df_vals.transform([np.sqrt, np.exp]))

3. GroupBy Integration: Group-Level Normalization

In GroupBy workflows, transform() calculates group statistics (such as group means) while broadcasting results back to match original DataFrame row counts.

import pandas as pd 

df_sales = pd.DataFrame({
    'DEPT': ['IT', 'IT', 'HR', 'HR'],
    'SALARY': [70000, 80000, 50000, 60000]
})

# Broadcast department mean salary to original rows
df_sales['DEPT_AVG'] = df_sales.groupby('DEPT')['SALARY'].transform('mean')
print(df_sales)

Expected Output:

  DEPT  SALARY  DEPT_AVG
0   IT   70000   75000.0
1   IT   80000   75000.0
2   HR   50000   55000.0
3   HR   60000   55000.0

4. Frequently Asked Questions (FAQs)

Q: How does transform() differ from apply()?
transform() must return a result of the same length as the input, whereas apply() allows aggregation reductions (returning single scalar values per column/group).

Q: Can transform() handle string functions?
Yes, standard Pandas aliases like 'sum', 'mean', 'sqrt', and 'abs' are supported directly as strings.

5. Common Errors & Troubleshooting

ValueError: Function did not transform
Cause: Supplying a function that reduces row counts or changes DataFrame dimensions.
Fix: Ensure custom functions return identical length output matching original row indices.
Interactive Companion Jupyter Notebook

Explore interactive code cells, dynamically generate classes, test type vs isinstance comparisons, and run self-validating assertions.

View on GitHub Open In Colab

6. Related Tutorials




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer