2016-12-11 172 views
-1

我知道這個問題相當微不足道,但這是我使用熊貓的第一天,所以請至少發佈一個鏈接到我應該閱讀的文檔。計算大熊貓的物品數

基本上,我不知道如何計算每列的項數。假設我有這樣一個數據幀:

df = pandas.DataFrame({ 
    "Grade": [1, 2, 1, 1, 2, 1, 2, 2, 1], 
    "Major": ["Science", "Art", "Engineering", "Science", "Science", "Science", "Science", "Engineering", "Engineering"]}) 

我希望以下結果:

Grade Major   Number 
1  Science   3 
1  Engineering  2 
1  Art    0 
2  Science   2 
2  Engineering  1 
2  Art    1 

回答

1

我認爲你需要groupby與聚集size

print (df.groupby(['Grade','Major']).size().reset_index(name='Number')) 
    Grade  Major Number 
0  1 Engineering  2 
1  1  Science  3 
2  2   Art  1 
3  2 Engineering  1 
4  2  Science  2 

如果需要添加缺少的值每組添加unstackstack

print (df.groupby(['Grade','Major']) 
     .size() 
     .unstack(fill_value=0) 
     .stack() 
     .reset_index(name='Number')) 
    Grade  Major Number 
0  1   Art  0 
1  1 Engineering  2 
2  1  Science  3 
3  2   Art  1 
4  2 Engineering  1 
5  2  Science  2