简体   繁体   English

Python 中的数据透视表(Pandas)

[英]Pivot Table in Python (Pandas)

I'm very new to python (using pandas).我对 python 很陌生(使用熊猫)。 Kindly help.请帮忙。

There are two columns in my dataframe - weight conversion (float) and sales_units (int).我的数据框中有两列 - 重量转换 (float) 和 sales_units (int)。 I simply want to group by (sum) the sales_units by weight_conversion.我只是想通过 weight_conversion 按(总和)sales_units 分组。

Sample Data样本数据

weight_conversion   sales_units
0.1                   1
0.1                   2
50                    100
50                    200
96.1                  20
314.4                  2
500                   100
500                   200

            

I have tried two ways:我尝试了两种方法:

  1. GROUP BY IN PANDAS :在熊猫中分组:

df.groupby(['weight_conversion'])['Sales_Unit'].sum()

  1. PIVOT TABLE IN PANDAS:熊猫中的数据透视表:

    df.pivot_table(index = 'weight_conversion', values='Sales_Unit', aggfunc ='sum') df.pivot_table(index = 'weight_conversion', values='Sales_Unit', aggfunc ='sum')

Required Output: I need a simple pivot table where I have rows as weight_conversion along with sum of sales units.所需输出:我需要一个简单的数据透视表,其中有行作为 weight_conversion 以及销售单位的总和。

The output I'm getting in Python Pandas is as follows (so weird): weight_conversion我在 Python Pandas 中得到的输出如下(太奇怪了): weight_conversion

0       3300000000000000000000000000034000000000000000...
0.1     0000100001000000000000001000000020050000000000...
0.2     0000000000000000000000000000001000000001100000...
0.3                           000000000000000000000300000
0.4     0000000000100000000000000000000000000000000001...
                            ...                        
90                                        000000000102009
92      0000200011000000000000010001000000000000000020...
92.1                            0000001000000000000000003
96      2000000000000000000000000000000000001100000000...
96.1    0000000000000000000000000000000000000000000000...

Name: Sales_Unit, Length: 96, dtype: object名称:Sales_Unit,长度:96,数据类型:对象

sample output样本输出

weight_conversion   sales_units
0.1                   3
50                    300
96.1                  20
314.4                  2
500                   300

Please help.**请帮忙。**

I dont think you need PIVOT table for the sample output you have given.我认为您提供的示例输出不需要 PIVOT 表。 Below worked as for the required output you mentioned以下是您提到的所需输出

 df = pd.DataFrame({"weight_conversion":[0.1,0.1,50,50,96.1,314.4,500,500], "sales_units":[1,2,100,200,20,2,100,200]}) df.groupby('weight_conversion').agg({'sales_units':'sum'}).reset_index() Output:
在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM