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
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.
DataFrame.transform(func, axis=0, *args, **kwargs)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).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]))
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
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.
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.