pandas 按年和月分组 Panda Pivot Table

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47804865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:54:32  来源:igfitidea点击:

Group by Year and Month Panda Pivot Table

pythonpython-3.xpandas

提问by Huzaifa M Aamir

I have data like this

我有这样的数据

    Date    LoanOfficer     User_Name       Loan_Number
0   2017-11-30 00:00:00 Mark Evans      underwriterx    1100000293
1   2017-11-30 00:00:00 Kimberly White  underwritery    1100004947
2   2017-11-30 00:00:00 DClair Phillips underwriterz    1100007224

I've created df pivot table like this:

我已经像这样创建了 df 数据透视表:

pd.pivot_table(df,index=["User_Name","LoanOfficer"],
               values=["Loan_Number"],
               aggfunc='count',fill_value=0,
               columns=["Date"]
                      )

However I need the Date column to be grouped by Year and Month. I was looking at other solutions of resampling the dataframe and then applying the pivot but it only does it for Month and Days. Any help would be appreciated

但是,我需要按年和月对日期列进行分组。我正在研究重新采样数据框然后应用数据透视表的其他解决方案,但它仅适用于月和日。任何帮助,将不胜感激

回答by YOBEN_S

You can convert you Date column to %Y-%m , then do the pivot_table

您可以将 Date 列转换为 %Y-%m ,然后执行 pivot_table

df.Date=pd.to_datetime(df.Date)
df.Date=df.Date.dt.strftime('%Y-%m')
df
Out[143]: 
      Date      LoanOfficer     User_Name  Loan_Number
0  2017-11       Mark Evans  underwriterx   1100000293
1  2017-11   Kimberly White  underwritery   1100004947
2  2017-11  DClair Phillips  underwriterz   1100007224

pd.pivot_table(df,index=["User_Name","LoanOfficer"],
               values=["Loan_Number"],
               aggfunc='count',fill_value=0,
               columns=["Date"]
                      )
Out[144]: 
                             Loan_Number
Date                             2017-11
User_Name    LoanOfficer                
underwriterx Mark Evans                1
underwritery Kimberly White            1
underwriterz DClair Phillips           1