The transform() method

The transform function in groupby is used to perform transformation operations on a groupby object. For example, we could replace NaN values in the groupby object using the fillna method. The resultant object after using transform has the same size as the original groupby object.

Let's introduce NAs into the sample sales data. The following code injects NAs into 25% of the records:

na_df = sales_data[["Sales", "Quantity", "Discount", "Profit", "Category"]].set_index("Category").mask(np.random.random(sales_data[["Sales", "Quantity", "Discount", "Profit"]].shape) < .25)na_df.head(10)

The following will be the output:

Snapshot of data with NAs inserted

Now, the four quantitative variables contain NAs in 25% of ...

Get Mastering pandas - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.