如何使用Pandas在Python中创建透视表

您所在的位置:网站首页 表格怎么生成透视图形图片 如何使用Pandas在Python中创建透视表

如何使用Pandas在Python中创建透视表

2024-07-12 23:50| 来源: 网络整理| 查看: 265

如何使用Pandas在Python中创建透视表

数据透视表是一个统计表,它总结了一个像大数据集这样的实质性表格。它是数据处理的一部分。透视表中的这种总结可能包括平均数、中位数、总和或其他统计术语。数据透视表最初与MS Excel有关,但我们可以在Python中使用Pandas的dataframe.pivot()方法来创建一个数据透视表。

语法 : dataframe.pivot(self, index=None, columns=None, values=None, aggfunc)

参数 – index:列,用于制作新框架的索引。 columns:列为新框架的列。 values:列,用于填充新框架的值。 aggfunc:函数,函数列表,dict,默认numpy.mean

示例 1: 让我们首先创建一个包括水果销售的数据框架。

# importing pandas import pandas as pd    # creating dataframe df = pd.DataFrame({'Product' : ['Carrots', 'Broccoli', 'Banana', 'Banana',                                 'Beans', 'Orange', 'Broccoli', 'Banana'],                    'Category' : ['Vegetable', 'Vegetable', 'Fruit', 'Fruit',                                  'Vegetable', 'Fruit', 'Vegetable', 'Fruit'],                    'Quantity' : [8, 5, 3, 4, 5, 9, 11, 8],                    'Amount' : [270, 239, 617, 384, 626, 610, 62, 90]}) df

输出:

如何使用Pandas在Python中创建透视表?

获得每个产品的总销售额。

# creating pivot table of total sales # product-wise aggfunc = 'sum' will  # allow you to obtain the sum of sales # each product pivot = df.pivot_table(index =['Product'],                        values =['Amount'],                        aggfunc ='sum') print(pivot)

输出: 如何使用Pandas在Python中创建透视表?

获得每个类别的总销售额。

# creating pivot table of total  # sales category-wise aggfunc = 'sum' # will allow you to obtain the sum of # sales each product pivot = df.pivot_table(index =['Category'],                         values =['Amount'],                         aggfunc ='sum') print(pivot)

输出: 如何使用Pandas在Python中创建透视表?

获得类别和产品的总销售额。

# creating pivot table of sales # by product and category both # aggfunc = 'sum' will allow you # to obtain the sum of sales each # product pivot = df.pivot_table(index =['Product', 'Category'],                         values =['Amount'], aggfunc ='sum') print (pivot)

输出 – 如何使用Pandas在Python中创建透视表?

按类别获得平均数、中位数、最低销售量。

# creating pivot table of Mean, Median, # Minimum sale by category aggfunc = {'median', # 'mean', 'min'} will get median, mean and  # minimum of sales respectively pivot = df.pivot_table(index =['Category'], values =['Amount'],                         aggfunc ={'median', 'mean', 'min'}) print (pivot)

输出 – 如何使用Pandas在Python中创建透视表?

按产品获取平均数、中位数、最小销售量。

# creating pivot table of Mean, Median, # Minimum sale by product aggfunc = {'median', # 'mean', 'min'} will get median, mean and # minimum of sales respectively pivot = df.pivot_table(index =['Product'], values =['Amount'],                        aggfunc ={'median', 'mean', 'min'}) print (pivot)

输出: 如何使用Pandas在Python中创建透视表?



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3