📜  如何计算 Pandas 中列的百分比?

📅  最后修改于: 2022-05-13 01:54:26.526000             🧑  作者: Mango

如何计算 Pandas 中列的百分比?

百分比是通过将值除以所有值的总和然后将总和乘以 100 的数学公式计算的。这也适用于 Pandas Dataframes。在这里,pandas 系列的预定义sum()方法用于计算列的所有值的总和。

公式:

df[percent] = (df['column_name'] / df['column_name'].sum()) * 100

示例 1:

Python3
# Import required libraries
import pandas as pd
import numpy as np
   
# Dictionary
df1 = {
     'Name': ['abc', 'bcd', 'cde',
             'def', 'efg', 'fgh',
             'ghi'],
     'Math_score': [52, 87, 49,
                   74, 28, 59,
                   48]}
   
# Create a DataFrame
df1 = pd.DataFrame(df1, 
                   columns = ['Name',
                             'Math_score'])
  
# Calculating Percentage
df1['percent'] = (df1['Math_score'] / 
                  df1['Math_score'].sum()) * 100
  
# Show the dataframe
df1


Python3
# Import pandas library
import pandas as pd
   
# Dictionary
df1 = {
     'Name': ['abc', 'bcd', 'cde',
             'def', 'efg', 'fgh',
             'ghi'],
      'Math_score': [52, 87, 49,
                    74, 28, 59,
                    48],
       'Eng_score': [34, 67, 25, 
                    89, 92, 45,
                    86]
}
   
# Create a DataFrame
df1 = pd.DataFrame(df1, 
                   columns = ['Name',
                   'Math_score','Eng_score'])
  
# Calculate Percentage
df1['Eng_percent'] = (df1['Eng_score'] / 
                      df1['Eng_score'].sum()) * 100
# Show the dataframe
df1


输出:

带有百分比的数据框

示例 2:

Python3

# Import pandas library
import pandas as pd
   
# Dictionary
df1 = {
     'Name': ['abc', 'bcd', 'cde',
             'def', 'efg', 'fgh',
             'ghi'],
      'Math_score': [52, 87, 49,
                    74, 28, 59,
                    48],
       'Eng_score': [34, 67, 25, 
                    89, 92, 45,
                    86]
}
   
# Create a DataFrame
df1 = pd.DataFrame(df1, 
                   columns = ['Name',
                   'Math_score','Eng_score'])
  
# Calculate Percentage
df1['Eng_percent'] = (df1['Eng_score'] / 
                      df1['Eng_score'].sum()) * 100
# Show the dataframe
df1

输出:

百分比为 2 的数据框