Pandas Series: transform() function
Call function on self producing a Series in Pandas
The transform() function is used to call function on self producing a Series with transformed values and that has the same axis length as self.
Syntax:
Series.transform(self, func, axis=0, *args, **kwargs)
Parameters:
Name | Description | Type/Default Value | Required / Optional |
---|---|---|---|
func | Function to use for transforming the data. If a function, must either work when passed a Series or when passed to Series.apply. Accepted combinations are:
|
unction, str, list or dict | Required |
axis | Parameter needed for compatibility with DataFrame | {0 or ‘index’} | Required |
args | Positional arguments to pass to func. | Required | |
**kwds | Keyword arguments to pass to func. | Required |
Returns:Series
A Series that must have the same length as self.
Raises: ValueError- If the returned Series has a different length than self.
Example:
Python-Pandas Code:
import numpy as np
import pandas as pd
df = pd.DataFrame({'P': range(4), 'Q': range(2, 6)})
df
Output:
P Q 0 0 2 1 1 3 2 2 4 3 3 5
Python-Pandas Code:
import numpy as np
import pandas as pd
df = pd.DataFrame({'P': range(4), 'Q': range(2, 6)})
df.transform(lambda x: x + 2)
Output:
P Q 0 2 4 1 3 5 2 4 6 3 5 7
Example - Even though the resulting Series must have the same length as the input Series, it is possible to provide several input functions:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series(range(4))
s
Output:
0 0 1 1 2 2 3 3 dtype: int64
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series(range(4))
s.transform([np.sqrt, np.exp])
Output:
sqrt exp 0 0.000000 1.000000 1 1.000000 2.718282 2 1.414214 7.389056 3 1.732051 20.085537
Previous: Aggregation with pandas series
Next: Map values of Pandas Series
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics