python - 熊猫每月数据的百分比值
问题描述
我有一个示例数据:
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)
解决方案
您可以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
推荐阅读
- ssas - MDX 查询事实计数
- database - 具有一对多关系的 2 个表上的附加表
- javascript - 是否有可能获得
- javascript - element.width 正在返回未定义
- python - 使用 ItemLoader 跨多个响应加载项目文件
- ruby-on-rails - 在 Rails 中将参数传递给回调
- javascript - React-Router 链接按钮不带路由器?
- wpf - 通过双击标题最大化窗口时,WPF DataGrid MouseLeftButtonUp 被触发
- json - 我在哪里可以获得假的商店 JSON 以便我可以练习获取数据?
- android-gradle-plugin - Gradle 使用 Fabric 插件构建 Crashlytics 和 groovy 插件 DSL