How to calculate the Percentage of a column in Pandas?

How to calculate the Percentage of a column in Pandas?

To calculate the percentage of a column in a Pandas DataFrame, you'd typically want to compute the percentage based on the sum or another metric of that column. Here's how you can calculate the percentage of each value in a column relative to the sum of the column:

Percentage based on column sum:

  1. Using a Single Line of Code:

    import pandas as pd # Sample data df = pd.DataFrame({ 'Value': [100, 200, 300, 400] }) # Calculate percentage df['Percentage'] = df['Value'] / df['Value'].sum() * 100 print(df) 

    Output:

     Value Percentage 0 100 10.0 1 200 20.0 2 300 30.0 3 400 40.0 
  2. Using apply() Method:

    If you prefer to use the apply() method for some reason, you can do it this way:

    total = df['Value'].sum() df['Percentage'] = df['Value'].apply(lambda x: (x / total) * 100) 

The output will be the same as above.

Note: This example demonstrates the percentage computation for each row in a column relative to the column's sum. Depending on your specific need, you might want to compute percentages based on other metrics, so you'd adjust the code accordingly.


More Tags

pyodbc legend absolute-path fluent bidirectional linestyle highcharts variables glsl core-image

More Programming Guides

Other Guides

More Programming Examples