如何在Pandas的数据透视表中包含百分比

如何在Pandas的数据透视表中包含百分比

Seaborn是一个惊人的可视化库,用于在Python中绘制统计图形。它提供了漂亮的默认样式和调色板,使统计图更具吸引力。它建立在matplotlib库的基础上,也与pandas的数据结构紧密结合。

透视表是用来总结数据的,其中包括各种统计概念。为了计算透视表中某一类别的百分比,我们要计算类别计数与总计数的比率。下面是一些例子,描述了如何在数据透视表中包含百分比。

示例 1:

在下图中,已经为给定的数据集创建了透视表,其中的性别百分比已经被计算出来。

如何在Pandas的数据透视表中包含百分比?

# importing pandas library
import pandas as pd
  
# creating dataframe
df = pd.DataFrame({'Name': ['John', 'Sammy', 'Stephan', 'Joe', 'Emily', 'Tom'],
                   'Gender': ['Male', 'Female', 'Male',
                              'Female', 'Female', 'Male'],
                   'Age': [45, 6, 4, 36, 12, 43]})
print("Dataset")
print(df)
print("-"*40)
  
# categorizing in age groups
def age_bucket(age):
    if age <= 18:
        return "<18"
    else:
        return ">18"
  
df['Age Group'] = df['Age'].apply(age_bucket)
  
# calculating gender percentage
gender = pd.DataFrame(df.Gender.value_counts(normalize=True)*100).reset_index()
gender.columns = ['Gender', '%Gender']
df = pd.merge(left=df, right=gender, how='inner', on=['Gender'])
  
# creating pivot table
table = pd.pivot_table(df, index=['Gender', '%Gender', 'Age Group'], 
                       values=['Name'], aggfunc={'Name': 'count',})
  
# display table
print("Table")
print(table)
Python

输出:

如何在Pandas的数据透视表中包含百分比?

示例 2:

下面是另一个例子,它描述了如何计算一个变量在某一列中占其总和的百分比。

# importing required libraries
import pandas as pd
import matplotlib.pyplot as plt
  
# creating dataframe
df = pd.DataFrame({
    'Name': ['John', 'Emily', 'Smith', 'Joe'],
    'Gender': ['Male', 'Female', 'Male', 'Female'],
    'Salary(in )': [20, 40, 35, 28]})
  
print("Dataset")
print(df)
print("-"*40)
  
# creating pivot table
table = pd.pivot_table(df, index=['Gender', 'Name'])
  
# calculating percentage
table['% Income'] = (table['Salary(in)']/table['Salary(in $)'].sum())*100
  
# display table
print("Pivot Table")
print(table)
Python

输出:

如何在Pandas的数据透视表中包含百分比?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册