python - 如何使用 pandas 交叉表汇总年度犯罪计数?

标签 python pandas

我正在对芝加哥犯罪数据进行回归分析,我想对每个地区的年度犯罪计数进行汇总。我知道芝加哥犯罪数据非常大,但可以公开访问以了解这些数据。现在我做了 5 年期间每个地区的总犯罪计数,但我只是想看看每个地区的年度犯罪计数,我只对排名前 5 的犯罪感兴趣。

数据

这里是 keggle 上的芝加哥犯罪数据:chicago crime data

我做了什么:

crimes_2012 = pd.read_csv('Chicago_Crimes_2012_to_2017.csv', sep=',', error_bad_lines=False)
crimes_2012.drop_duplicates(subset=['ID', 'Case Number', 'Date'], inplace=True)
crimes_2012.drop(['Unnamed: 0','Case Number','IUCR','FBI Code','Updated On',
                  'X Coordinate','Y Coordinate'], inplace = True, axis = 1)
crimes_2012 = crimes_2012.dropna(axis = 0, how = 'any')

以下是我对每个地区的犯罪总数所做的操作:

df=crimes_2012[['Primary Type', 'Location Description', 'Community Area']]
crime_catg = df.groupby(['Community Name', 'Primary Type'])['Primary Type'].count().unstack()
crime_catg = crime_catg[['THEFT','BATTERY', 'CRIMINAL DAMAGE', 'NARCOTICS', 'ASSAULT']]

所需输出:

我想获取每个地区/社区区域每种犯罪类型的年度计数。像这样的东西:

enter image description here

有什么方便的方法可以轻松做到这一点吗?我尝试了 pandas 的交叉表,但实际上没有得到正确的输出。如何完成这个任务?

最佳答案

以下是创建所需交叉表的方法。有几个问题,首先您需要将列 'Date' 转换为日期时间类型。然后,我们将过滤 crimes_2012 框架的子集,仅包含您感兴趣的 5 项犯罪 boolean indexingSeries.isin .

最后,创建 crosstab并使用sort_index以获得所需的形状。

crimes_2012['Date'] = pd.to_datetime(crimes_2012['Date'], format='%m/%d/%Y %H:%M:%S %p')

top_5_crimes = ['THEFT','BATTERY', 'CRIMINAL DAMAGE', 'NARCOTICS', 'ASSAULT']

df = crimes_2012[crimes_2012['Primary Type'].isin(top_5_crimes)]

df_cross = (pd.crosstab(index=df['Community Area'],
                        columns=[df['Date'].dt.year, df['Primary Type']])
            .sort_index(axis=1, level=[1, 0]))

然后,如果您需要展平列级别,请使用:

df_cross.columns = ['{} {}'.format(crime, year) for year, crime in df_cross.columns]

[输出]

print(df_cross.head())

                ASSAULT 2012  ASSAULT 2013  ASSAULT 2014  ASSAULT 2015  \
Community Area                                                           
0.0                        0             0             0             0   
1.0                      340           303           257           234   
2.0                      254           225           201           166   
3.0                      244           277           210           233   
4.0                      124           111            85            99   

                ASSAULT 2016  BATTERY 2012  BATTERY 2013  BATTERY 2014  \
Community Area                                                           
0.0                        0             0             0             0   
1.0                      227           991           866           776   
2.0                      198           658           669           574   
3.0                      241           736           667           593   
4.0                       93           354           352           319   

                BATTERY 2015  BATTERY 2016  ...  NARCOTICS 2012  \
Community Area                              ...                   
0.0                        0             0  ...               0   
1.0                      666           724  ...             485   
2.0                      544           534  ...             230   
3.0                      661           653  ...             735   
4.0                      288           288  ...             111   

                NARCOTICS 2013  NARCOTICS 2014  NARCOTICS 2015  \
Community Area                                                   
0.0                          0               0               0   
1.0                        362             278             205   
2.0                        216             173             157   
3.0                        482             519             271   
4.0                         61             102              78   

                NARCOTICS 2016  THEFT 2012  THEFT 2013  THEFT 2014  \
Community Area                                                       
0.0                          0           0           0           0   
1.0                         79        1043        1004         811   
2.0                         79         976         991         794   
3.0                        100        1338        1134         952   
4.0                         36         691         689         507   

                THEFT 2015  THEFT 2016  
Community Area                          
0.0                      0           0  
1.0                    845         851  
2.0                    669         694  
3.0                    879         968  
4.0                    499         514  

关于python - 如何使用 pandas 交叉表汇总年度犯罪计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55750813/

相关文章:

Python:为DataFrame中每个组的第一个观察值赋值

python - 缺少 1 个必需的仅关键字参数

python - CountVectorizer(分析器 ='char_wb')未按预期工作

python - chardet 在 python 3 中运行不正确

python - 在 OpenCV 中检测由图案包围的形状

python - dataframe KeyError,虽然它存在

python - 如何在多索引数据框中选择第一级最后一个键中的行?

python - 在 pandas groupby 中聚合日期的有效方法

python - 提取多个实例正则表达式python

python - 在 Tkinter 的表格中显示数据的最佳方式是什么?