机器学习-数据科学库-day6
pandas学习
动手练习
#!usr/bin/env python
# -*- coding:utf-8 _*-
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
#设置行不限制数量
pd.set_option('display.max_rows',50)
#最后的的参数可以限制输出行的数量
#设置列不限制数量
pd.set_option('display.max_columns',50)
#最后的的参数可以限制输出列的数量
#设置value的显示长度为80,默认为50
pd.set_option('max_colwidth',50)
df=pd.read_csv("./911.csv")
# print(df.head(10))
# print("*"*100)
# print(df.info())
#分类在title列的:前面字段
#获取分类
# print(df["title"])
# print(df["title"].str.split(":"))
temp_list=(df["title"].str.split(":")).tolist()
# print(temp_list)
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:
zeros_df[cate][df["title"].str.contains(cate)]=1
# print(zeros_df)
sum_ret=zeros_df.sum(axis=0)
print(sum_ret)
#换一种方式赋值,迭代次数多(249737次),运行时间很长,不推荐!
# for i in range(df.shape[0]):
# zeros_df.loc[i,temp_list[i][0]]=1
# print(zeros_df)
运行结果:
EMS 124844.0
Traffic 87465.0
Fire 37432.0
dtype: float64
Process finished with exit code 0
方法2:#给df添加一列cate,用groupby的方法可以统计数量
#!usr/bin/env python
# -*- coding:utf-8 _*-
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
#设置行不限制数量
pd.set_option('display.max_rows',50)
#最后的的参数可以限制输出行的数量
#设置列不限制数量
pd.set_option('display.max_columns',50)
#最后的的参数可以限制输出列的数量
#设置value的显示长度为80,默认为50
pd.set_option('max_colwidth',50)
df=pd.read_csv("./911.csv")
# print(df.head(5))
# print("*"*100)
# print(df.info())
#分类在title列的:前面字段
#获取分类
# print(df["title"])
# print(df["title"].str.split(":"))
temp_list=(df["title"].str.split(":")).tolist()
# print(temp_list)
cate_list=[i[0] for i in temp_list]
# print(cate_list)
#给df添加一列cate,groupby的方法可以统计数量
cate_df=pd.DataFrame(np.array(cate_list).reshape((df.shape[0],1)),columns=["cate"])
# print(cate_df)
df["cate"]=cate_df
print(df.head(10))
print("*"*100)
print(df.groupby(by="cate").count()["title"])
运行结果:
lat lng desc \
0 40.297876 -75.581294 REINDEER CT & DEAD END; NEW HANOVER; Station ...
1 40.258061 -75.264680 BRIAR PATH & WHITEMARSH LN; HATFIELD TOWNSHIP...
2 40.121182 -75.351975 HAWS AVE; NORRISTOWN; 2015-12-10 @ 14:39:21-St...
3 40.116153 -75.343513 AIRY ST & SWEDE ST; NORRISTOWN; Station 308A;...
4 40.251492 -75.603350 CHERRYWOOD CT & DEAD END; LOWER POTTSGROVE; S...
5 40.253473 -75.283245 CANNON AVE & W 9TH ST; LANSDALE; Station 345;...
6 40.182111 -75.127795 LAUREL AVE & OAKDALE AVE; HORSHAM; Station 35...
7 40.217286 -75.405182 COLLEGEVILLE RD & LYWISKI RD; SKIPPACK; Stati...
8 40.289027 -75.399590 MAIN ST & OLD SUMNEYTOWN PIKE; LOWER SALFORD;...
9 40.102398 -75.291458 BLUEROUTE & RAMP I476 NB TO CHEMICAL RD; PLYM...
zip title timeStamp \
0 19525.0 EMS: BACK PAINS/INJURY 2015-12-10 17:10:52
1 19446.0 EMS: DIABETIC EMERGENCY 2015-12-10 17:29:21
2 19401.0 Fire: GAS-ODOR/LEAK 2015-12-10 14:39:21
3 19401.0 EMS: CARDIAC EMERGENCY 2015-12-10 16:47:36
4 NaN EMS: DIZZINESS 2015-12-10 16:56:52
5 19446.0 EMS: HEAD INJURY 2015-12-10 15:39:04
6 19044.0 EMS: NAUSEA/VOMITING 2015-12-10 16:46:48
7 19426.0 EMS: RESPIRATORY EMERGENCY 2015-12-10 16:17:05
8 19438.0 EMS: SYNCOPAL EPISODE 2015-12-10 16:51:42
9 19462.0 Traffic: VEHICLE ACCIDENT - 2015-12-10 17:35:41
twp addr e cate
0 NEW HANOVER REINDEER CT & DEAD END 1 EMS
1 HATFIELD TOWNSHIP BRIAR PATH & WHITEMARSH LN 1 EMS
2 NORRISTOWN HAWS AVE 1 Fire
3 NORRISTOWN AIRY ST & SWEDE ST 1 EMS
4 LOWER POTTSGROVE CHERRYWOOD CT & DEAD END 1 EMS
5 LANSDALE CANNON AVE & W 9TH ST 1 EMS
6 HORSHAM LAUREL AVE & OAKDALE AVE 1 EMS
7 SKIPPACK COLLEGEVILLE RD & LYWISKI RD 1 EMS
8 LOWER SALFORD MAIN ST & OLD SUMNEYTOWN PIKE 1 EMS
9 PLYMOUTH BLUEROUTE & RAMP I476 NB TO CHEMICAL RD 1 Traffic
****************************************************************************************************
cate
EMS 124840
Fire 37432
Traffic 87465
Name: title, dtype: int64
pandas中的时间序列
不管在什么行业,时间序列都是一种非常重要的数据形式,很多统计数据以及数据的规律也都和时间序列有着非常重要的联系
而且在pandas中处理时间序列是非常简单的
生成一段时间范围
pd.date_range(start=None, end=None, periods=None, freq=‘D’)
start和end以及freq配合能够生成start和end范围内以频率freq的一组时间索引
start和periods以及freq配合能够生成从start开始的频率为freq的periods个时间索引
#!usr/bin/env python
# -*- coding:utf-8 _*-
import pandas as pd
import numpy as np
t1=pd.date_range(start="20171230",end="20180131",freq="D")
print(t1)
t2=pd.date_range(start="20171230",end="20180131",freq="10D")
print(t2)
t3=pd.date_range(start="20171230",periods=10,freq="10D")
print(t3)
t4=pd.date_range(start="20171230",periods=10,freq="M")
print(t4)
t5=pd.date_range(start="20171230",periods=10,freq="MS")
print(t5)
print("*"*100)
index=pd.date_range("20170101",periods=10)
df = pd.DataFrame(np.random.rand(10),index=index)
print(df)
运行结果:
C:\ANACONDA\python.exe C:/Users/Lenovo/PycharmProjects/Code/day06/test_date_range.py
DatetimeIndex(['2017-12-30', '2017-12-31', '2018-01-01', '2018-01-02',
'2018-01-03', '2018-01-04', '2018-01-05', '2018-01-06',
'2018-01-07', '2018-01-08', '2018-01-09', '2018-01-10',
'2018-01-11', '2018-01-12', '2018-01-13', '2018-01-14',
'2018-01-15', '2018-01-16', '2018-01-17', '2018-01-18',
'2018-01-19', '2018-01-20', '2018-01-21', '2018-01-22',
'2018-01-23', '2018-01-24', '2018-01-25', '2018-01-26',
'2018-01-27', '2018-01-28', '2018-01-29', '2018-01-30',
'2018-01-31'],
dtype='datetime64[ns]', freq='D')
DatetimeIndex(['2017-12-30', '2018-01-09', '2018-01-19', '2018-01-29'], dtype='datetime64[ns]', freq='10D')
DatetimeIndex(['2017-12-30', '2018-01-09', '2018-01-19', '2018-01-29',
'2018-02-08', '2018-02-18', '2018-02-28', '2018-03-10',
'2018-03-20', '2018-03-30'],
dtype='datetime64[ns]', freq='10D')
DatetimeIndex(['2017-12-31', '2018-01-31', '2018-02-28', '2018-03-31',
'2018-04-30', '2018-05-31', '2018-06-30', '2018-07-31',
'2018-08-31', '2018-09-30'],
dtype='datetime64[ns]', freq='M')
DatetimeIndex(['2018-01-01', '2018-02-01', '2018-03-01', '2018-04-01',
'2018-05-01', '2018-06-01', '2018-07-01', '2018-08-01',
'2018-09-01', '2018-10-01'],
dtype='datetime64[ns]', freq='MS')
****************************************************************************************************
0
2017-01-01 0.927442
2017-01-02 0.860891
2017-01-03 0.708140
2017-01-04 0.836886
2017-01-05 0.296686
2017-01-06 0.344187
2017-01-07 0.271763
2017-01-08 0.398221
2017-01-09 0.439301
2017-01-10 0.062734
Process finished with exit code 0
关于频率的更多缩写
在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数据中不同月份电话次数的变化情况
#!usr/bin/env python
# -*- coding:utf-8 _*-
import time
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
#设置行不限制数量
pd.set_option('display.max_rows',50)
#最后的的参数可以限制输出行的数量
#设置列不限制数量
pd.set_option('display.max_columns',50)
#最后的的参数可以限制输出列的数量
#设置value的显示长度为80,默认为50
pd.set_option('max_colwidth',50)
df=pd.read_csv("./911.csv")
# print(df.head(5))
# print("*"*100)
# print(df.info())
df["timeStamp"]=pd.to_datetime(df["timeStamp"])
df.set_index("timeStamp",inplace=True)
# print(df.head(5))
count_by_month= df.resample("M").count()["title"]
print(count_by_month)
#画图
_x=count_by_month.index
_y=count_by_month.values
# print(_x)
# print("*"*100)
# print(_y)
# print("*"*100)
# for i in _x:
# print(dir(i))
# break
#改变_x的格式,使其没有分秒显示
_x=[i.strftime("%Y%m%d") for i in _x]
# print(_x)
# print("*"*100)
plt.figure(figsize=(20,12),dpi=80)
plt.plot(range(len(_x)),_y)
plt.xticks(range(len(_x)),_x,rotation=45)
plt.show()
运行结果:
C:\ANACONDA\python.exe C:/Users/Lenovo/PycharmProjects/Code/day06/page148.py
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
Process finished with exit code 0
- 统计出911数据中不同月份不同类型的电话的次数的变化情况
#!usr/bin/env python
# -*- coding:utf-8 _*-
import time
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
#设置行不限制数量
pd.set_option('display.max_rows',50)
#最后的的参数可以限制输出行的数量
#设置列不限制数量
pd.set_option('display.max_columns',50)
#最后的的参数可以限制输出列的数量
#设置value的显示长度为80,默认为50
pd.set_option('max_colwidth',50)
df=pd.read_csv("./911.csv")
# print(df.head(5))
# print("*"*100)
# print(df.info())
#添加列,表示分类
temp_list=(df["title"].str.split(":")).tolist()
# print(temp_list)
cate_list=[i[0] for i in temp_list]
df["cate"]=pd.DataFrame(np.array(cate_list).reshape((df.shape[0],1)))
# print(df.head(10))
#把时间字符串转为时间类型,并设置为索引
df["timeStamp"]=pd.to_datetime(df["timeStamp"])
df.set_index("timeStamp",inplace=True)
# print(df.head(10))
#画图设置
plt.figure(figsize=(20,12),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
_y=count_by_month.values
#改变_x的格式,使其没有分秒显示
_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()
运行结果:
PeriodIndex
之前所学习的DatetimeIndex可以理解为时间戳
那么现在我们要学习的PeriodIndex可以理解为时间段
periods = pd.PeriodIndex(year=data[“year”],month=data[“month”],day=data[“day”],hour=data[“hour”],freq=“H”)
那么如果给这个时间段降采样呢?
data = df.set_index(periods).resample(“10D”).mean()
动手练习
请绘制出5个城市的PM2.5随时间的变化情况
#!usr/bin/env python
# -*- coding:utf-8 _*-
import time
import pandas as pd
from matplotlib import pyplot as plt
#设置行不限制数量
pd.set_option('display.max_rows',50)
#最后的的参数可以限制输出行的数量
#设置列不限制数量
pd.set_option('display.max_columns',50)
#最后的的参数可以限制输出列的数量
#设置value的显示长度为80,默认为50
pd.set_option('max_colwidth',50)
file_path="./PM2.5/BeijingPM20100101_20151231.csv"
df=pd.read_csv(file_path)
# 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")
# print(period)
# print(type(period))
#给df添加一列"datetime"的数据(period的时间类型)
df["datetime"]=period
# print(df.head(5))
#把datetime 设置为索引
df.set_index("datetime",inplace=True)
# print(df.head(5))
#进行降采样
df=df.resample("7D").mean()
# print(df.head(10))
# print(df.shape)
#处理缺失数据,删除缺失数据nan(降采用后求均值,所以不存在nan,故无需删除)
# print(df["PM_US Post"])
data=df["PM_US Post"]
# print(data)
data_china=df["PM_Dongsi"]
#画图
_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
print(len(_x),len(_x_china))
plt.figure(figsize=(20,12),dpi=80)
plt.plot(range(len(_x)),_y,label="US_Post")
plt.plot(range(len(_x_china)),_y_china,label="CN_Post")
plt.xticks(range(0,len(_x),10),list(_x)[::10],rotation=45)
plt.legend(loc="best")
plt.show()
运行结果: