2014-10-01 25 views
1

我的大部分數據分析需求都從R切換到Python,並且遇到以下問題。可能是我對groupby()的概念理解的結果。只有一列後()

我有一個熊貓數據框,並試圖根據多個列彙總數據。下面的代碼得到了我想要的。

df = df[(df["Lead Source"] != "chase") & (df["Lead Source"] != "SNE")] 
ndf = df[["Date", "Lead Source", "Model Group", "Leads"]].groupby(["Date", "Lead Source"]).sum() 

enter image description here

這看起來很棒,但我注意到,有運行以下時,只有一個「真正的」列。 (FYI ndf2只是NDF的複印件)

ndf2.columns 
Out[39]: Index([u'Leads'], dtype='object') 

而且,行的索引顯示,這並不完全符合我所期待的。

enter image description here

我怎樣才能調整行,使列名出現在第一行。輸出應如下所示。

Date  Lead Source Leads 
1/1/2014 ...   ... 
      ...   ... 
      ...   ... 

回答

2

你可以使用:

ndf.reset_index() 

注意,GROUPBY操作創建一個帶有MultiIndex一個數據幀。由於您按DateLead Source分組,因此這些是MultiIndex的級別名稱。 DateLead Source之所以在列名下面顯示一行是因爲熊貓正試圖表明這些是索引級別名稱,而不是列。 (看看ndf.index.names。)撥打電話reset_index將索引級別移動到列並對索引重新編號。

或者更好的是,使用as_index=False option調用groupby時:

ndf = (df[["Date", "Lead Source", "Model Group", "Leads"]] 
     .groupby(["Date", "Lead Source"], as_index=False).sum()) 

聚集時,將as_index=False將阻止使用索引值的分組值。