Transformations
Contrary to aggregations, transformations do not reduce an array of values to a single value but, rather, maintain the shape of the calling object. This particular recipe may seem rather mundane coming from the previous section on aggregations, but transformations and aggregations will end up being very complementary tools to calculate things like the “% total of group” later in the cookbook.
How to do it
Let’s create a small pd.Series
:
ser = pd.Series([-1, 0, 1], dtype=pd.Int64Dtype())
Much like we saw with pd.Series.agg
before, pd.Series.transform
can accept a list of functions to apply. However, whereas pd.Series.agg
expected these functions to return a single value, pd.Series.transform
expects these functions to return a pd.Series
with the same index and shape:
def adds_one(ser: pd.Series) -> pd.Series:
return ser + 1
ser.transform(["abs", adds_one])
abs adds_one
0 1 0
1 0 1...