You can use the following syntax to calculate the percentage of a total within groups in pandas: df[' values_var '] / df. groupby (' group_var ')[' values_var ']. transform (' sum ') The following example shows how to use this syntax in practice., You can calculate the percentage of the total within each group using DataFrame.groupby() along with DataFrame.agg(), DataFrame.transform(), and DataFrame.apply() with lambda function. You can also calculate the percentage by using sum and divide functions., Learn various techniques to calculate the percentage of total sales per office by state using Pandas' powerful GroupBy functionality., To calculate the percentage of each value within a group, you divide the individual value by the total value for that group and multiply by 100. Practical Example. Let's say we have a DataFrame with sales data: To calculate the percentage of total sales for each product category: # Sample DataFrame . 'Sales Amount': [1000, 500, 800, 200]}, The most elegant way to find percentages across columns or index is to use pd.crosstab. Sample Data df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3, 'office_id': list(range(1, 7)) * 2, 'sales': [np.random.randint(100000, 999999) for _ in range(12)]}), Calculating current ratio with Python is super easy. How to convert a column to a category in pandas? One trick you can use in pandas is to convert a column to a category, then use those category values for your label encoding: obj_df[“body_style”] = obj_df[“body_style”].astype(‘category’) obj_df.dtypes.