现在我们有2015到2017年25万条911的紧急电话的数据,请统计出出这些数据中不同类型的紧急情况的次数。
方法一
import pandas as pd
import numpy as np
df = pd.read_csv("./911.csv")
#获取分类
print(df["title"].str.split(": ") )
temp_list = df["title"].str.split(": ").tolist()
cate_list = list(set([i[0] for i in temp_list]))
print(cate_list)
#构造全为0的数组
zeros_df = pd.Dataframe(np.zeros((df.shape[0],len(cate_list))),columns=cate_list)
print(zeros_df)
#赋值
for cate in cate_list:
# print(df["title"].str.contains(cate))
zeros_df[cate][df["title"].str.contains(cate)] = 1
# break
print(zeros_df)
sum_ret = zeros_df.sum(axis=0)
print(sum_ret)
运行结果:
0 [EMS, BACK PAINS/INJURY]
1 [EMS, DIABETIC EMERGENCY]
2 [Fire, GAS-ODOR/LEAK]
3 [EMS, CARDIAC EMERGENCY]
4 [EMS, DIZZINESS]
...
249732 [EMS, OVERDOSE]
249733 [EMS, FALL VICTIM]
249734 [EMS, VEHICLE ACCIDENT]
249735 [Fire, FIRE ALARM]
249736 [Traffic, VEHICLE ACCIDENT -]
Name: title, Length: 249737, dtype: object
['Traffic', 'Fire', 'EMS']
Traffic Fire EMS
0 0.0 0.0 0.0
1 0.0 0.0 0.0
2 0.0 0.0 0.0
3 0.0 0.0 0.0
4 0.0 0.0 0.0
... ... ... ...
249732 0.0 0.0 0.0
249733 0.0 0.0 0.0
249734 0.0 0.0 0.0
249735 0.0 0.0 0.0
249736 0.0 0.0 0.0
[249737 rows x 3 columns]
Traffic Fire EMS
0 0.0 0.0 1.0
1 0.0 0.0 1.0
2 0.0 1.0 0.0
3 0.0 0.0 1.0
4 0.0 0.0 1.0
... ... ... ...
249732 0.0 0.0 1.0
249733 0.0 0.0 1.0
249734 0.0 0.0 1.0
249735 0.0 1.0 0.0
249736 1.0 0.0 0.0
[249737 rows x 3 columns]
Traffic 87465.0
Fire 37432.0
EMS 124844.0
dtype: float64
方法二
import pandas as pd
import numpy as np
df = pd.read_csv("./911.csv")
print(df.head(5))
#获取分类
# print()df["title"].str.split(": ")
temp_list = df["title"].str.split(": ").tolist()
cate_list = [i[0] for i in temp_list]
#往df中新添加一列“cate”
df["cate"] = pd.Dataframe(np.array(cate_list).reshape((df.shape[0],1)))
# print(df.head(5))
print(df.groupby(by="cate").count()["title"])
运行结果:
lat lng ... addr e 0 40.297876 -75.581294 ... REINDEER CT & DEAD END 1 1 40.258061 -75.264680 ... BRIAR PATH & WHITEMARSH LN 1 2 40.121182 -75.351975 ... HAWS AVE 1 3 40.116153 -75.343513 ... AIRY ST & SWEDE ST 1 4 40.251492 -75.603350 ... CHERRYWOOD CT & DEAD END 1 [5 rows x 9 columns] cate EMS 124840 Fire 37432 Traffic 87465 Name: title, dtype: int64pandas中的时间序列
时间序列都是一种非常重要的数据形式,很多统计数据以及数据的规律也都和时间序列有着非常重要的联系。
而且在pandas中处理时间序列是非常简单的。
pd.date_range(start=None, end=None, periods=None, freq='D')
start和end以及freq配合能够生成start和end范围内以频率freq的一组时间索引。
start和periods以及freq配合能够生成从start开始的频率为freq的periods个时间索引。
关于频率的更多缩写 在Dataframe中使用时间序列index=pd.date_range("20170101",periods=10)
df = pd.Dataframe(np.random.rand(10),index=index)
回到最开始的911数据的案例中,我们可以使用pandas提供的方法把时间字符串转化为时间序列
df["timeStamp"] = pd.to_datetime(df["timeStamp"],format="")
format参数大部分情况下可以不用写,但是对于pandas无法格式化的时间字符串,我们可以使用该参数,比如包含中文。
pandas重采样重采样:指的是将时间序列从一个频率转化为另一个频率进行处理的过程,将高频率数据转化为低频率数据为降采样,低频率转化为高频率为升采样。
pandas提供了一个resample的方法来帮助我们实现频率转化。
练习:
- 统计出911数据中不同月份电话次数的变化情况。
import pandas as pd
from matplotlib import pyplot as plt
df = pd.read_csv("./911.csv")
df["timeStamp"] = pd.to_datetime(df["timeStamp"])
df.set_index("timeStamp",inplace=True)
#统计出911数据中不同月份电话次数
count_by_month = df.resample("M").count()["title"]
print(count_by_month)
#画图
_x = count_by_month.index
_y = count_by_month.values
#格式化
_x = [i.strftime("%Y%m%d") for i in _x]
plt.figure(figsize=(20,8),dpi=80)
plt.plot(range(len(_x)),_y)
plt.xticks(range(len(_x)),_x,rotation=45)
plt.show()
运行结果:
timeStamp 2015-12-31 7916 2016-01-31 13096 2016-02-29 11396 2016-03-31 11059 2016-04-30 11287 2016-05-31 11374 2016-06-30 11732 2016-07-31 12088 2016-08-31 11904 2016-09-30 11669 2016-10-31 12502 2016-11-30 12091 2016-12-31 12162 2017-01-31 11605 2017-02-28 10267 2017-03-31 11684 2017-04-30 11056 2017-05-31 11719 2017-06-30 12333 2017-07-31 11768 2017-08-31 11753 2017-09-30 7276 Freq: M, Name: title, dtype: int64
- 统计出911数据中不同月份不同类型的电话的次数的变化情况。
#911数据中不同月份不同类型的电话的次数的变化情况
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
#把时间字符串转为时间类型,并设置为索引
df = pd.read_csv("./911.csv")
df["timeStamp"] = pd.to_datetime(df["timeStamp"])
#添加列,表示分类
temp_list = df["title"].str.split(": ").tolist()
cate_list = [i[0] for i in temp_list]
# print(np.array(cate_list).reshape((df.shape[0],1)))
df["cate"] = pd.Dataframe(np.array(cate_list).reshape((df.shape[0],1)))
#pd.Dataframe按数字索引,所以在之后改索引
df.set_index("timeStamp",inplace=True)
print(df.head(1))
plt.figure(figsize=(20, 8), dpi=80)
#分组
for group_name,group_data in df.groupby(by="cate"):
#对不同的分类都进行绘图
count_by_month = group_data.resample("M").count()["title"]
# 画图
_x = count_by_month.index
print(_x)
_y = count_by_month.values
print(_y)
_x = [i.strftime("%Y%m%d") for i in _x]
plt.plot(range(len(_x)), _y, label=group_name)
plt.xticks(range(len(_x)), _x, rotation=45)
plt.legend(loc="best")
plt.show()
运行结果:
lat lng ... e cate
timeStamp ...
2015-12-10 17:10:52 40.297876 -75.581294 ... 1 EMS
[1 rows x 9 columns]
DatetimeIndex(['2015-12-31', '2016-01-31', '2016-02-29', '2016-03-31',
'2016-04-30', '2016-05-31', '2016-06-30', '2016-07-31',
'2016-08-31', '2016-09-30', '2016-10-31', '2016-11-30',
'2016-12-31', '2017-01-31', '2017-02-28', '2017-03-31',
'2017-04-30', '2017-05-31', '2017-06-30', '2017-07-31',
'2017-08-31', '2017-09-30'],
dtype='datetime64[ns]', name='timeStamp', freq='M')
[3898 6063 5413 5832 5684 5730 5720 6029 6005 5750 6039 5838 6024 6082
5417 5913 5780 5948 6030 5974 5882 3789]
DatetimeIndex(['2015-12-31', '2016-01-31', '2016-02-29', '2016-03-31',
'2016-04-30', '2016-05-31', '2016-06-30', '2016-07-31',
'2016-08-31', '2016-09-30', '2016-10-31', '2016-11-30',
'2016-12-31', '2017-01-31', '2017-02-28', '2017-03-31',
'2017-04-30', '2017-05-31', '2017-06-30', '2017-07-31',
'2017-08-31', '2017-09-30'],
dtype='datetime64[ns]', name='timeStamp', freq='M')
[1095 1904 1868 1589 1717 1573 1787 1898 1907 1793 1930 1765 1846 1658
1462 1634 1614 1670 1986 1754 1862 1120]
DatetimeIndex(['2015-12-31', '2016-01-31', '2016-02-29', '2016-03-31',
'2016-04-30', '2016-05-31', '2016-06-30', '2016-07-31',
'2016-08-31', '2016-09-30', '2016-10-31', '2016-11-30',
'2016-12-31', '2017-01-31', '2017-02-28', '2017-03-31',
'2017-04-30', '2017-05-31', '2017-06-30', '2017-07-31',
'2017-08-31', '2017-09-30'],
dtype='datetime64[ns]', name='timeStamp', freq='M')
[2923 5129 4115 3638 3886 4071 4225 4161 3992 4126 4533 4488 4292 3865
3388 4137 3662 4101 4317 4040 4009 2367]
PeriodIndex
之前所学习的DatetimeIndex可以理解为时间戳,那么现在我们要学习的PeriodIndex可以理解为时间段。
periods = pd.PeriodIndex(year=data["year"],month=data["month"],day=data["day"],hour=data["hour"],freq="H")
可以把分开的时间字符串通过periodIndex的方法转化为pandas的时间类型。
思考题现在我们有北上广、深圳、和沈阳5个城市空气质量数据,请绘制出5个城市的PM2.5随时间的变化情况。
mport pandas as pd
from matplotlib import pyplot as plt
file_path = "./PM2.5/BeijingPM20100101_20151231.csv"
df = pd.read_csv(file_path)
#显示所有的列
pd.set_option('display.max_columns', None)
# print(df.head())
# print(df.info())
#把分开的时间字符串通过periodIndex的方法转化为pandas的时间类型
period = pd.PeriodIndex(year=df["year"],month=df["month"],day=df["day"],hour=df["hour"],freq="H")
df["datetime"] = period #type为PeriodIndex
# print(df.head(10))
#把datetime 设置为索引
df.set_index("datetime",inplace=True)
#进行降采样
df = df.resample("7D").mean()
# print(df.head())
#处理缺失数据,删除缺失数据
# print(df["PM_US Post"])
data = df["PM_US Post"]
data_china = df["PM_Nongzhanguan"]
# print(data_china.head(100))
#画图
_x = data.index
_x = [i.strftime("%Y%m%d") for i in _x]
_x_china = [i.strftime("%Y%m%d") for i in data_china.index]
_y = data.values
_y_china = data_china.values
plt.figure(figsize=(20,8),dpi=80)
plt.plot(range(len(_x)),_y,label="US_POST",alpha=0.7)
plt.plot(range(len(_x_china)),_y_china,label="CN_POST",alpha=0.7)
plt.xticks(range(0,len(_x_china),10),list(_x_china)[::10],rotation=45)
plt.legend(loc="best")
plt.show()
运行结果:



