卖游戏币网站制作/2345网址导航下载桌面
动手
现在我们有北上广、成都、和沈阳5个城市空气质量数据,请绘制出5个城市的PM2.5随时间的变化情况
观察这组数据中的时间结构,并不是字符串,这个时候我们应该怎么办?
df.info()
=====================================
=====================================
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 52584 entries, 0 to 52583
Data columns (total 18 columns):# Column Non-Null Count Dtype
--- ------ -------------- ----- 0 No 52584 non-null int64 1 year 52584 non-null int64 2 month 52584 non-null int64 3 day 52584 non-null int64 4 hour 52584 non-null int64 5 season 52584 non-null int64 6 PM_Dongsi 25052 non-null float647 PM_Dongsihuan 20508 non-null float648 PM_Nongzhanguan 24931 non-null float649 PM_US Post 50387 non-null float6410 DEWP 52579 non-null float6411 HUMI 52245 non-null float6412 PRES 52245 non-null float6413 TEMP 52579 non-null float6414 cbwd 52579 non-null object 15 Iws 52579 non-null float6416 precipitation 52100 non-null float6417 Iprec 52100 non-null float64
dtypes: float64(11), int64(6), object(1)
memory usage: 7.2+ MB
年月日小时是分开的,并且他是每隔一个小时统计一次数据
解
先以美国发布的关于北京的PM2.5的数据为准,绘制图形
这个时间和我们常见的时间是不一样的:时间是分开的,分成了年月日小时四个部分
我们需要将这四个部分拼到一起构成完整的时间
PeriodIndex
DatetimeIndex–时间戳,时间点
PeriodIndex–时间段
结果是一个PeriodIndex类型的数据
结合之前我们对DatetimeIndex的学习,如果我们想要对这样(PeriodIndex类型)的数据进行重采样的操作,我们应该怎么办呢?
第一步就是将这个数据设置为df的索引
PeriodIndex和DatetimeIndex的区别
我们构造时间序列的方式不一样,
- PeriodIndex
pd.PeriodIndex(year=df["year"],month=df["month"],day=df["day"],hour=df["hour"],freq="H")
- DatetimeIndex:
pd.date_range(start=None, end=None, periods=None, freq='D')
请绘制出5个城市的PM2.5随时间的变化情况
方法都是一样的,我们绘制出一个城市和我们绘制出五个城市的效果是一样的
处理缺失数据的常见思路:
- 删除
- 填充数据(均值、中位数、众数……)
这地方处理缺失值的思路:
- 删除这一列中含有缺失值的行
- 用当前这一天的缺失值或当前这一个月的平均值来填充缺失值数据
思路一:绘制全部数据的图形
# -*- coding: utf-8 -*-'''
@Time : 2020/12/24 15:52
@Author : yuhui
@Email : 3476237164@qq.com
@FileName: pandas_15.py
@Software: PyCharm
'''"""
39【pandas案例】01PM2.5案例现在我们有北上广、成都、和沈阳5个城市空气质量数据,请绘制出5个城市的PM2.5随时间的变化情况观察这组数据中的时间结构,并不是字符串,这个时候我们应该怎么办?
"""import pandas as pd
pd.options.display.max_columns=999import numpy as npfrom matplotlib import pyplot as pltplt.rcParams["font.sans-serif"]=["KaiTi"] # 解决中文乱码的问题 设置字体为楷体
plt.rcParams["font.family"]="sans-serif" # 解决符号无法显示的问题
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像时负号'-'显示为方块的问题"""设置图形大小和图片品质"""
fig=plt.figure(figsize=(16,9),dpi=100,
)df=pd.read_csv("../data/PM2.5/BeijingPM20100101_20151231.csv")"""在df中新增一列:时间,并将其设置为index"""
# 将年月日小时四段时间合并
# 把分开的时间字符串通过PeriodIndex方法转化为pandas的时间序列
periodindex=pd.PeriodIndex(year=df["year"],month=df["month"],day=df["day"],hour=df["hour"],freq="H")# 在df中新增一列:完整的时间 full_time
df["full_time"]=periodindex# 将full_time这一列设置为index
df.set_index("full_time",inplace=True)"""思路一:绘制出所有的数据""""""处理缺失值"""
# 删除PM_US Post这一列中缺失值所在的行
# 方法一
# df=df[pd.notnull(df["PM_US Post"])]# 方法二
data=df["PM_US Post"].dropna() # series"""数据可视化 绘制折线图"""
# 准备数据
_x=data.index
_y=data.values# 绘制折线图
plt.plot(range(len(_x)),_y)# 绘制x轴刻度信息
plt.xticks(range(0,len(_x),10),_x[::10])# 绘制网格线
plt.grid(linestyle=":", # 线型color="#6495ED", # 颜色 CornflowerBlue 矢车菊的蓝色 #6495ED 100,149,237alpha=0.4, # 透明度
)# print(data)plt.show()
运行结果是这样的
虽然我们绘制的是折线图,但是由于数据量太过于庞大,看起来就像是条形图一样,看起来十分的不方便,我们是无法从这里面获取到我们想要的信息的
思路二:对df进行降采样
# -*- coding: utf-8 -*-'''
@Time : 2020/12/24 22:24
@Author : yuhui
@Email : 3476237164@qq.com
@FileName: pandas_15_2.py
@Software: PyCharm
'''"""
39【pandas案例】01PM2.5案例现在我们有北上广、成都、和沈阳5个城市空气质量数据,请绘制出5个城市的PM2.5随时间的变化情况观察这组数据中的时间结构,并不是字符串,这个时候我们应该怎么办?思路二:对full_time这一列进行降采样操作,绘制出一部分数据"""import pandas as pd
pd.options.display.max_columns=999import numpy as npfrom matplotlib import pyplot as pltplt.rcParams["font.sans-serif"]=["KaiTi"] # 解决中文乱码的问题 设置字体为楷体
plt.rcParams["font.family"]="sans-serif" # 解决符号无法显示的问题
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像时负号'-'显示为方块的问题"""设置图形大小和图片品质"""
fig=plt.figure(figsize=(16,9),dpi=100,
)df=pd.read_csv("../data/PM2.5/BeijingPM20100101_20151231.csv")"""在df中新增一列:时间,并将其设置为index"""
# 将年月日小时四段时间合并
# 把分开的时间字符串通过PeriodIndex方法转化为pandas的时间序列
periodindex=pd.PeriodIndex(year=df["year"],month=df["month"],day=df["day"],hour=df["hour"],freq="H")# 在df中新增一列:完整的时间 full_time
df["full_time"]=periodindex# 将full_time这一列设置为index
df.set_index("full_time",inplace=True)# 对df进行降采样操作
data=df.resample("7D")["PM_US Post"].mean()# 注意:这时候我们就不需要处理缺失值了
# 因为我们在计算平均值的时候不会将缺失值计算在内"""数据可视化 绘制折线图"""
# 准备数据
_x=data.index
# 时间格式化
_x=[i.strftime("%Y%m%d") for i in _x]_y=data.values# 绘制折线图
plt.plot(range(len(_x)),_y)# 绘制x轴刻度信息
plt.xticks(range(0,len(_x),25),_x[::25])# 绘制网格线
plt.grid(linestyle=":", # 线型color="#6495ED", # 颜色 CornflowerBlue 矢车菊的蓝色 #6495ED 100,149,237alpha=0.4, # 透明度
)print(data)plt.show()
将中国的数据和美国的数据放在同一张图上
# -*- coding: utf-8 -*-'''
@Time : 2020/12/24 22:46
@Author : yuhui
@Email : 3476237164@qq.com
@FileName: pandas_16.py
@Software: PyCharm
'''"""39【pandas案例】01PM2.5案例将中国的数据和美国的数据绘制在同一张图上降采样"""import pandas as pd
pd.options.display.max_columns=999from matplotlib import pyplot as pltplt.rcParams["font.sans-serif"]=["KaiTi"] # 解决中文乱码的问题 设置字体为楷体
plt.rcParams["font.family"]="sans-serif" # 解决符号无法显示的问题
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像时负号'-'显示为方块的问题"""设置图形大小和图片品质"""
fig=plt.figure(figsize=(16,9),dpi=100,
)df=pd.read_csv("../data/PM2.5/BeijingPM20100101_20151231.csv")"""在df中新增一列:时间"""
# 将年月日小时四段时间合并
periodindex=pd.PeriodIndex(year=df["year"],month=df["month"],day=df["day"],hour=df["hour"],freq="H")# 在df中新增一列:完整的时间 full_time
df["full_time"]=periodindex# 设置full_time这一列为df的索引
df.set_index("full_time",inplace=True)# 对df进行降采样操作
PM_US_Post=df.resample("7D")["PM_US Post"].mean()
PM_Dongsi=df.resample("7D")["PM_Dongsi"].mean()"""数据可视化 折线图"""
# 准备数据
_x_PM_US_Post=PM_US_Post.index
_x_PM_US_Post=[i.strftime("%Y%m%d") for i in _x_PM_US_Post]_x_PM_Dongsi=PM_Dongsi.index
_x_PM_Dongsi=[i.strftime("%Y%m%d") for i in _x_PM_Dongsi]_y_PM_US_Post=PM_US_Post.values
_y_PM_Dongsi=PM_Dongsi.values# 绘制图形
plt.plot(range(len(_x_PM_US_Post)),_y_PM_US_Post,label="PM_US Post")
plt.plot(range(len(_x_PM_Dongsi)),_y_PM_Dongsi,label="PM_Dongsi")# 添加图例
plt.legend(loc="best")# 绘制x轴刻度信息
# 绘制x轴刻度信息
plt.xticks(range(0,len(_x_PM_Dongsi),25),_x_PM_Dongsi[::25])# 绘制网格线
plt.grid(linestyle=":", # 线型color="#6495ED", # 颜色 CornflowerBlue 矢车菊的蓝色 #6495ED 100,149,237alpha=0.4, # 透明度
)plt.show()