2016-12-22 70 views
2

這裏的每一列是我的數據框:熊貓 - 集團本身

col1 col2 col3 col4 
0 True False True True 
1 True True False False 
2 False False True False 
3 True True False True 

有沒有辦法來組我的數據,使我得到類似以下,其中該表中的數字出現的次數:

 col2   col3  col4 
     True False True False True False 
col1   
True 2 1  x x  x x 
False 0 1  x x  x x 

非常感謝您的幫助!

回答

2

col1設置爲索引軸。執行stack操作將其重塑爲長格式的系列對象。

multiindex系列的groupby級0和1生成並計算它們各自的值計數。然後,unstack和排序兩者的索引行和縱列,任選被@jezrael填充NaNs以0

(df.set_index('col1').stack().groupby(level=[0,1]).value_counts().unstack(level=[1,2]) 
    .sort_index(ascending=False, axis=1).sort_index(ascending=False).fillna(0).astype(int)) 

enter image description here

甲每評論進一步簡化的解決方案:

(df.set_index('col1').stack().groupby(level=[0,1]).value_counts() 
    .sort_index(ascending=[False, True, False]).unstack([1,2]).fillna(0).astype(int)) 

enter image description here

此外,您可以按降序對索引軸進行排序以獲取y我們期望的o/p。

+1

我刪除評論,因爲'真''False'在索引中對換,對不起;( – jezrael

+1

和好的解決方案,+1 – jezrael

+1

這很完美,非常感謝! –