在Python中格式化聚合数据帧的标题

时间:2018-09-25 10:32:00

标签: python pandas dataframe

我有一个数据框,如下所示:-

,issue_name,doc_id,doc_type,doc_title
0,The App keeps crashing / restarting / hanging,5b519e219b989aaf3db06917,GUIDE,Restart the device
1,The App keeps crashing / restarting / hanging,5b519e219b989aaf3db06917,GUIDE,Restart the device
2,The App keeps crashing / restarting / hanging,5b51a24d9b989aaf3db0691a,GUIDE,Fix the App
3,The App keeps crashing / restarting / hanging,5b51a24d9b989aaf3db0691a,GUIDE,Fix the App
4,The App keeps crashing / restarting / hanging,5b519e219b989aaf3db06917,GUIDE,Restart the device
5,The App keeps crashing / restarting / hanging,5b519e219b989aaf3db06917,GUIDE,Restart the device

当我使用下面的代码汇总计数时:-

dfreturns = pd.DataFrame(Guidedocdetails, columns=['issue_name','doc_id','doc_type','doc_title'])
dfreturns.to_csv('ReturnGuideDocDetails.csv')
dfreturnguidecount = dfreturns.groupby(['issue_name','doc_type','doc_title']).agg(['count'])
dfreturnguidecount.to_csv('Return_guideid_counts.csv') 

我得到的输出如下:enter image description here

如何删除顶部的doc_id和多余的行。我想要输出如下: enter image description here

请帮助我了解如何实现这一目标。

应用以下代码后:-

dfnonreturnguidecount = (dfnonreturns.groupby(['issue_name','doc_type','doc_title'])['issue_name'].count().reset_index(name='count'))
dfnonreturnguidecount.to_csv('NonReturn_guideid_counts.csv')

输出:- enter image description here

1 个答案:

答案 0 :(得分:1)

我认为需要使用GroupBy.sizeGroupBy.count在列中删除MultiIndex

returnguidecount = (dfreturns.groupby(['issue_name','doc_type','doc_title'])
                             .size()
                             .reset_index(name='count'))

returnguidecount = (dfreturns.groupby(['issue_name','doc_type','doc_title'])['issue_name']
                             .count()
                             .reset_index(name='count'))

print (returnguidecount) 
                                      issue_name doc_type           doc_title  \
0  The App keeps crashing / restarting / hanging    GUIDE         Fix the App   
1  The App keeps crashing / restarting / hanging    GUIDE  Restart the device   

   count  
0      2  
1      4  

差异是count排除groupby之后指定列中的NaNs值。