统计911不同月份中不同类型的紧急电话类型

统计911不同月份中不同类型的紧急电话类型

这个数据分析涉及到三个库,分别是pandas、numpy、matplotlib,这三个库都是学习数据分析要掌握的库。

导入库

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

读取数据

data = pd.read_csv('I:crack/DATA/911.csv')
pd.set_option('display.max_columns',1000)
pd.set_option('display.max_colwidth',1000)
print(data.info())

这里的pd.set_option(‘display.max_columns’,1000)和pd.set_option(‘display.max_colwidth’,1000)主要是为了在显示的时候让数据显示更多,方便我们观察,不用这两行代码也是可以的。
data.info()主要是用来观察读取的数据的基本信息,比如有多少列数据,列索引都是什么,缺失了多少数据,这些都可以很好的展现出来。
这个911的数据csv文件可以从这里(https://pan.baidu.com/s/1HlOvzj3fAl39I58nJ2V8wQ)提取出来,密码是:3fyp
或者上kaggle网站中下载(https://www.kaggle.com/mchirico/montcoalert)

时间序列

#把时间那一列的字符串转化为时间序列,然后代替时间那列数据
data['timeStamp'] = pd.to_datetime(data['timeStamp'],format="")
#然后重新定义行索引
data.set_index('timeStamp',inplace= True)
#把索引转化为月
data_1 = data.resample('M').count()['title']

pandas中的时间序列是一个非常强大的功能,可以制造时间序列,也可以把一些字符串强制转化为时间序列,这里所用到的就是把字符串强制转化成时间序列,然后采用降采样的方式来重新定义时间序列,最后代替行索引。

分类统计

group = data.groupby(by = 'time')
x = []
y_1 = []
y_2 = []
y_3 = []
for group_time,group_cate in group:
    print(group_time)
    x.append(group_time)
    group_cate.set_index('time',inplace= True)
    group_cate_1 = group_cate.groupby(by='cate').count()['title']
    y_1.append(group_cate_1[0])
    y_2.append(group_cate_1[1])
    y_3.append(group_cate_1[2])
    print(group_cate_1.index)

这里用到的是pandas的分类汇总中的groupby,groupby返回的是一个可迭代类型的对象,所以就用循环的方式来提取出分类的值,这里分别有四个空列表,x列表是用来接收年份的,y_1是来接收统计第一种紧急电话类型在每个月拨打的次数,y_2就是第二种类型,y_3就是第三种。

绘图

#设置中文字体
plt.rcParams['font.family'] = 'SimHei'
#定义图片大小
fig,ax = plt.subplots(figsize = (40,8))
#绘图
plt.xticks(range(len(x)),x,rotation=45)
#设置柱状图的宽度
bar_width = 0.3
x_1 = list(range(len(x)))
x_2 = [i + bar_width for i in x_1]
x_3 = [i + bar_width*2 for i in x_1]
rect_1 = plt.bar(x_1,y_1,label=group_cate_1.index[0],width=bar_width)
rect_2 = plt.bar(x_2,y_2,label=group_cate_1.index[1],width=bar_width)
rect_3 = plt.bar(x_3,y_3,label=group_cate_1.index[2],width=bar_width)
plt.legend()
#绘制网格线
plt.grid()

#设置座标
for rect_1s in rect_1:
    height = rect_1s.get_height()
    plt.text(rect_1s.get_x() + rect_1s.get_width()/2,1.03*height,'%s'%float(height),ha='center')

for rect_2s in rect_2:
    heights = rect_2s.get_height()
    plt.text(rect_2s.get_x() + rect_2s.get_width()/2,heights,int(heights),ha='center')

for rect_3s in rect_3:
    heights = rect_3s.get_height()
    plt.text(rect_3s.get_x() + rect_3s.get_width()/2,heights,int(heights),ha='center')
#设置标题
plt.title('统计911不同月份中不同类型的紧急电话类型')
plt.show()

这里是用条形图中的柱状图绘制,如果不懂绘制柱状图,可以参考我的第二篇博客,或者去(https://matplotlib.org/gallery/index.html)网站去查看和学习

源码

'''
统计911不同月份中不同类型的紧急电话类型
时间序列
creat on April 9,2019
@Author 小明
'''
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

#读取数据
data = pd.read_csv('I:crack/DATA/911.csv')
pd.set_option('display.max_columns',1000)
pd.set_option('display.max_colwidth',1000)
# print(data.head(1))
print(data.info())

#首先把紧急电话类型提取出来
emergency_data = data['title'].str.split(': ')
emergency_data_1 = list([i[0] for i in emergency_data])
emergency_data_2 = pd.Series(emergency_data_1)
# print(emergency_data_2.value_counts())

#也可以用赋值0和1的方法来统计,先构造全为零的数组
df_zeor = pd.DataFrame(np.zeros((data.shape[0],len(set(emergency_data_1)))),columns=set(emergency_data_1))
# print(df_zeor)
#然后赋值
for cate in set(emergency_data_1):
    df_zeor[cate][data['title'].str.contains(cate)] = 1
# print(df_zeor.sum())
#把时间那一列的字符串转化为时间序列,然后代替时间那列数据
data['timeStamp'] = pd.to_datetime(data['timeStamp'],format="")
#然后重新定义行索引
data.set_index('timeStamp',inplace= True)
# print(data.head(3))

#把索引转化为月
data_1 = data.resample('M').count()['title']
# print(data_1)

#把每月每种类型的紧急电话统计起来
#首先把时间提取到月,然后在插入一列为时间列
time = [i.strftime("%Y-%m") for i in data.index]
data['time'] = time
#在数据后面加一列,数据为电话类型
data['cate'] = emergency_data_1
# print(data.head(2))

#然后分类统计起来
# print(emergency_count)
# emergency_count_1 = emergency_count.groupby(by=data['cate']).count()
group = data.groupby(by = 'time')
x = []
y_1 = []
y_2 = []
y_3 = []
for group_time,group_cate in group:
    print(group_time)
    x.append(group_time)
    group_cate.set_index('time',inplace= True)
    group_cate_1 = group_cate.groupby(by='cate').count()['title']
    y_1.append(group_cate_1[0])
    y_2.append(group_cate_1[1])
    y_3.append(group_cate_1[2])
    print(group_cate_1.index)
    # print(group_cate_1.values[0])

#设置中文字体
plt.rcParams['font.family'] = 'SimHei'
#定义图片大小
fig,ax = plt.subplots(figsize = (40,8))
#绘图
plt.xticks(range(len(x)),x,rotation=45)
#设置柱状图的宽度
bar_width = 0.3
x_1 = list(range(len(x)))
x_2 = [i + bar_width for i in x_1]
x_3 = [i + bar_width*2 for i in x_1]
rect_1 = plt.bar(x_1,y_1,label=group_cate_1.index[0],width=bar_width)
rect_2 = plt.bar(x_2,y_2,label=group_cate_1.index[1],width=bar_width)
rect_3 = plt.bar(x_3,y_3,label=group_cate_1.index[2],width=bar_width)
plt.legend()
#绘制网格线
plt.grid()

#设置座标
for rect_1s in rect_1:
    height = rect_1s.get_height()
    plt.text(rect_1s.get_x() + rect_1s.get_width()/2,1.03*height,'%s'%float(height),ha='center')

for rect_2s in rect_2:
    heights = rect_2s.get_height()
    plt.text(rect_2s.get_x() + rect_2s.get_width()/2,heights,int(heights),ha='center')

for rect_3s in rect_3:
    heights = rect_3s.get_height()
    plt.text(rect_3s.get_x() + rect_3s.get_width()/2,heights,int(heights),ha='center')
#设置标题
plt.title('统计911不同月份中不同类型的紧急电话类型')
plt.show()

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章