首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用python的基于月销售额的枢轴表

使用python的基于月销售额的枢轴表
EN

Stack Overflow用户
提问于 2022-05-09 15:16:44
回答 2查看 143关注 0票数 0

我有一个按月销售的dataframe:

代码语言:javascript
运行
复制
customer product   month     revenue

     sam       A      2021-11      221
    
     tim       A      2021-12      220
    
     mi.       B      2021-10     213
    
     harry     A      2011-11    210
    
     eric.     A.      2021-10    213

需要输出:

产品A:

代码语言:javascript
运行
复制
customer product   2021-10.   2021-11.  2021-12
     
 sam       A        0            221      0  

 tim       A        0             0      220

 harry     A        0            210      0
 
 erIc     A.      213            0       0 

月份的格式是周期(M),.Any使用pivot_table function.There在python中这样做是很多产品,所以我需要在代码中指定产品名称。

EN

回答 2

Stack Overflow用户

发布于 2022-05-09 16:53:50

你是在找这样的东西吗?

代码语言:javascript
运行
复制
import numpy as np
import pandas as pd

data = pd.DataFrame(columns=["customer","product","month","revenue"])
data=data.append({"customer":"eric.","product":20,"month":"2011-10","revenue":213},ignore_index=True)
data=data.append({"customer":"harry","product":20,"month":"2011-11","revenue":210},ignore_index=True)
data=data.append({"customer":"tim","product":20,"month":"2011-12","revenue":220},ignore_index=True)
data=data.append({"customer":"sam","product":20,"month":"2021-11","revenue":221},ignore_index=True)
data=data.append({"customer":"mi","product":30,"month":"2021-10","revenue":213},ignore_index=True)
    
pivot_df = pd.pivot_table(data,values=["revenue"],index=["customer","product"],columns=["month"],fill_value=0,aggfunc=np.sum)
    
pivot_df_filtered = pivot_df.query("product == 20")

票数 0
EN

Stack Overflow用户

发布于 2022-05-09 20:55:00

也许这能帮上忙:

代码语言:javascript
运行
复制
g_data = data.groupby(['product','month','customer'])['revenue'].sum().unstack('month').fillna(0)

>>> g_data
'''
month             2021-10  2021-11  2021-12
product customer                           
A       eric.       213.0      0.0      0.0
        harry         0.0    210.0      0.0
        sam           0.0    221.0      0.0
        tim           0.0      0.0    220.0
B       mi.         213.0      0.0      0.0
'''

# filtering by product
prod_A = g_data.loc[('A'),]

>>> prod_A
'''
month     2021-10  2021-11  2021-12
customer                           
eric.       213.0      0.0      0.0
harry         0.0    210.0      0.0
sam           0.0    221.0      0.0
tim           0.0      0.0    220.0
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72174354

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档