首页 > 解决方案 > 熊猫每月数据的百分比值

问题描述

我有一个示例数据:

date        Product  Sales
2020-01-01.  Dell.    4
2020-01-01.  Apple.   6
2020-01-01.  Lenovo.  5
2020-01-02.  Dell.    2
2020-01-02.  Apple.   4
2020-01-02.  Lenovo.  3

我想创建另一个名为“月销售额百分比”的列,它是通过(产品的月销售额/该月所有产品的总销售额)* 100 获得的。

输出应如下所示:

date        Product  Sales. Percentage_monthly_sale
2020-01-01.  Dell.    4.      26.6 (4/15 *100)
2020-01-01.  Apple.   6.      40.0. (6/15*100)
2020-01-01.  Lenovo.  5.      33.3.  (5/15 *100)
2020-01-02.  Dell.    2.      22.2 (2/9 *100)
2020-01-02.  Apple.   4.      44.4 (4/9 *100)
2020-01-02.  Lenovo.  3.      33.3 (3/9 *100)

标签: pythonpandasdataframenumpydata-science

解决方案


您可以groupby transform使用lambda function

df['Percentage_daily_sale'] = df.groupby(
    ['date'])['Sales'].transform(lambda x: (x/x.sum()) * 100)

输出

          date  Product  Sales  Percentage_daily_sale
0  2020-01-01.    Dell.      4                  26.67
1  2020-01-01.   Apple.      6                  40.00
2  2020-01-01.  Lenovo.      5                  33.33
3  2020-01-02.    Dell.      2                  22.22
4  2020-01-02.   Apple.      4                  44.44
5  2020-01-02.  Lenovo.      3                  33.33

推荐阅读