All Courses

# What is the process for computing percentages by utilizing groupby in Pandas?

##### By Pp5344229@gmail.com, a month ago

How do I compute percentages using groupby in Pandas?

Percentages
Compute
groupby
pandas
##### Goutamp777

To compute percentages by utilizing groupby in Pandas, you can follow these steps:

2. Use the groupby() method to group the data by the desired column(s).
3. Apply the sum() or count() method to the grouped data to get the total count or sum for each group.
4. Divide the grouped data by the total count or sum for each group to get the percentage using the apply() method with a lambda function.
5. Assign the resulting percentage values to a new column in the DataFrame using the assign() method.

Here's an example code snippet:

```import pandas as pd

# group the data by a column
grouped_data = df.groupby('column_name')

# compute the sum or count for each group
total_counts = grouped_data['count_column'].sum()

# compute the percentage for each group
percentages = grouped_data.apply(lambda x: x['count_column'] / total_counts[x.name] * 100)

# assign the percentages to a new column
df = df.assign(percentage_column=percentages)

```

In this example, the code first groups the data by a column called "column_name". Then, it computes the sum of a count column for each group using the sum() method. Next, it computes the percentage for each group by dividing the count column by the total count for each group using a lambda function and the apply() method. Finally, it assigns the resulting percentages to a new column called "percentage_column" in the original DataFrame using the assign() method.

#### Live Masterclass on : "How Machine Get Trained in Machine Learning?" Mar 30th (7:00 PM) 516 Registered
More webinars

#### Related Discussions

Running random forest algorithm with one variable

View More