2015-11-16 119 views
2

我有超過33,000行的數據幀我想簡化其中:集團和計數在Python唯一值大熊貓據幀

    Crime type 
GeographyCode        
E01006687   Burglary 
E01007229   Anti-social behaviour 
E01007229   Anti-social behaviour 
E01007229   Anti-social behaviour 
E01007229   Burglary 
E01007229   Other theft 
E01007229   Other theft 
E01007229   Shoplifting 
E01007229   Theft from the person 
E01007230   Anti-social behaviour 
E01007230   Anti-social behaviour 
E01007230   Anti-social behaviour 
E01007230   Anti-social behaviour 
E01007230   Anti-social behaviour 
E01007230   Anti-social behaviour 
... 

有207個獨特的「GeographyCode」的值和12個獨特的價值「犯罪類型'。

我想創建一個新的數據框,它有207行,12列加上'GeographyCode'索引列,每列代表一個犯罪類型,幷包含該地理編碼內所有犯罪類型的發生次數。

事情是這樣的:

   Burglary Anti-social Theft Shoplifting etc... 
GeographyCode 
E01006687  1   3    9  5    ... 
E01007229  1   3    2  1    ... 
E01007230  0   6    12  5    ... 
... 

我已經嘗試了一些東西,但因爲沒有數值,我發現它真的很難得到我所需要的。

回答

6

你可以使用crosstab來計算的:

>>> pd.crosstab(df.index, df['Crime type']) 
Crime type  Anti-social behaviour Burglary Other theft Shoplifting ... 

E01006687       0   1   0   0 
E01007229       3   1   2   1 
E01007230       6   0   0   0 
+1

你實際的傳奇!這在整個週末一直在努力,並且在一個功能中得到解決。謝謝! – Cobain

+1

沒問題 - 很高興幫助! –