python中numpy、pandas、matplotlib的使用

python中numpy、pandas、matplotlib的使用

numpy

numpy是在python中做科学计算的基础库,重在数值计算,也是大部分python科学计算库的基础库,多用于在大型、多维数组上执行数值运算

生成数组(矩阵)

import numpy as np
#使用numpy生成数组
t1 = np.array([1,2,3,])
print(t1)
print(type(t1))

t2 = np.array(range(10))
print(t2)
print(type(t2))

t3 = np.arange(4,10,2)
print(t3)
print(type(t3))

print(t3.dtype)#输出存放的数据的类型

print("**********")
t4 = np.array(range(1,4),dtype = 'float')
print(t4)
print(t4.dtype)

在这里插入图片描述
下面介绍一些基本属性

import numpy as np

array = np.array([[1,2,3],[2,3,4]])
print(array)
print('number of dim:',array.ndim)#查看维数
print('shape:',array.shape)#查看形状
print('size:',array.size)#查看总共的元素数量

在这里插入图片描述
让我们现在来看看怎么创建各种各样,奇形怪状的数组

import numpy as np

a = np.zeros( (3,4))#生成一个全是零的矩阵
print(a)

b = np.ones( (2,5),dtype = np.int64)
print(b)

c = np.arange(12).reshape((3,4))#生成我们想要的形状
print(c)

d = np.linspace(0,10,5)#将一个线段等分为5段
print(d)

e = np.eye(5)#会输出一个5*5的方阵

在这里插入图片描述

基本运算操作

import numpy as np
a = np.array([10,20,30,40])
b = np.arange(4)

c = a - b#做减法
print('a - b:',c)

c = a + b#做加法
print('a + b:',c)

c = b**2#b的平方
print('b^2:',c)

c = 10*np.sin(a)#求sin值,用到的是弧度
print('10sin(a):',c)

#判断b中有哪些元素是小于3的
print(b)
print(b < 3)

a = np.array([[1,1],
              [0,1]])
b = np.arange(4).reshape((2,2))

c = a * b#这里仅仅是a和b中对应位置的元素相乘
c_dot = np.dot(a,b)#这里指的是矩阵乘法
print(c)
print(c_dot)
c_dot_2 = a.dot(b)#矩阵乘法的另一种形式
print(c_dot_2)

a = np.random.random((2,4))#随机生成一个【0,1】的2行4列的矩阵
print('求和:',np.sum(a))
print('最大值:',np.max(a))
print('最小值:',np.min(a))
print('对每一行进行求和:',np.sum(a,axis = 1))
print('对每一列进行求和:',np.sum(a,axis = 0))

print('**************************************************')

A = np.arange(2,14).reshape((3,4))
print(A)

print('最小值的索引为:',np.argmin(A))
print('最大值的索引为:',np.argmax(A))
print('矩阵的平均值为:',np.mean(A),A.mean(),np.average(A))
print('中位数为:',np.median(A))
print('前n项和:',np.cumsum(A))
A = np.arange(14,2,-1).reshape(3,4)
print(np.sort(A))#对A进行逐行排序
print(np.transpose(A))#对A进行转置
print(A.T)#对A进行转置
print(np.clip(A,5,9))#对A中小于5的数变5,大于9的数变9,在5和9之间的数不变

在这里插入图片描述

索引操作

import numpy as np
A = np.arange(3,15).reshape((3,4))
print(A[2])#输出第2行

print('输出每一行')
for row in A:
    print(row)
print('输出每一列')
for column in A.T:
    print(column)
print('输出每一个元素')
for item in A.flat:
    print(item)

在这里插入图片描述

array合并

import numpy as np

A = np.array([1,1,1])
B = np.array([2,2,2])

C = np.vstack((A,B))#vertical stack,上下合并

print(C)
print(A.shape,C.shape)

D = np.hstack((A,B))#horizontal stack,左右合并
print(D)
print(D.shape)

在这里插入图片描述

array分割

import numpy as np
A = np.arange(12).reshape((3,4))
print(A)

print(np.split(A,2,axis = 1))#对列进行分割
print(np.split(A,3,axis = 0))#对行进行分割
print(np.array_split(A,3,axis = 1))#对列进行不等分割

print(np.vsplit(A,3))#对行分割
print(np.hsplit(A,2))#对列分割

在这里插入图片描述

numpy copy & deep copy

import numpy as np
a = np.arange(4)
print("a:",a)
b = a;
print("b is a:",b is a)
a[0] = 5
print("b:",b)

c = a.copy()#deep copy
a[1] = 6
print("a:",a)
print("b:",b)
print("c:",c)

在这里插入图片描述

补充

  • 在numpy中轴可以理解为方向,用数字表示eg. np.arange(0,10).reshape((2,5))表示0轴长度为2,1轴长度为5

  • 参数解释
    .rand(d0,d1,…,dn)创建d0-d1维度的均匀分布的随机数数组,浮点数,范围从0-1
    .randn(d0,d1,…dn)创建d0-d1维度的标准正态分布随机数,浮点数,平均数0,标准差1
    .randint(low,high,(shape))从给定上下限范围选取随机整数,范围是low,high,形状是shape
    .uniform(low,high,(size))产生具有均匀分布的数组,low起始值,high结束值,size形状
    .normal(loc,scale,(size))从指定正态分布中随机抽取样本,分布中心是loc(概率分布的均值),标准差是scale,形状是size
    .seed(s)随机数种子,s是给定的种子值
  • nan: not a number表示不是一个数字

    inf: infinity表示无穷

  • numpy中nan注意点:

    1. 两个nan不相等
    2. np.nan != np.nan
    3. 判断数组中nan的个数 np.count_nonzero(t!=t)
    4. 判断是否为nan:np.isnan(array)
    5. nan和任何值计算都为nan
  • numpy中常用的统计函数

    求和:array.sum(axis = None)
    均值:array.mean(axis = None)
    中值:np.median(array,axis = None)
    最大值:array.max(axis = None)
    最小值:array.min(axis = None)
    极值:np.ptp(array,axis = None)//最大值与最小值之差
    标准差:array.std(axis = None)
    

pandas

numpy能帮我们处理数值型数据,到那会pandas除了可以处理数值型数据外还能帮我们处理其他型数据

pandas常用的数据类型:

​ (1)Series,一维,带标签数组

​ (2)DataFrame,二维,Series容器

了解Series

import pandas as pd
t = pd.Series([1,2,31,12,3,4])#简单的创建一个Series
print(type(t))
print(t)

t2 = pd.Series([1,23,2,2,1],index = list("abcde"))#指定索引值
print(t2)

temp_dict = {"name":"xiaohong","age":30,"tel":10086}
t3 = pd.Series(temp_dict)#通过字典创建Series
print(t3)

在这里插入图片描述
切片:直接传入start end或者步长即可

索引:一个的时候直接传入序号或者index,多个的时候传入序号或者index列表

import pandas as pd
t = pd.Series([0,1,2,3,4,5,6,7,8,9],index=list("ABCDEFGHIJ"))
print(t)
print(t.index)
print(t.values)

在这里插入图片描述

DataFrame

DataFrame对象既有行索引又有列索引

行索引,表明不同行,横向索引,叫index,0轴,axis = 0

列索引,表明不同列,纵向索引,叫columns,1轴,axis = 1

import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(12).reshape((3,4)),index=list("abc"),columns=list("WXYZ"))
print(df)#指定行索引用index,指定列索引用columns

dic = {"name":["xiaoming","xiaohong"],"age":[20,31],"tel":[10086,10010]}
df2 = pd.DataFrame(dic)#用字典生成DataFrame
print(df2)

l = [{"name":"xiaoming","age":20,"tel":10086},{"name":"xiaohong","age":20,"tel":10010},{"name":"xiaogang","age":18,"tel":10000}]
df3 = pd.DataFrame(l)#用一个list生成DataFrame
print(df3)

在这里插入图片描述

DataFrame描述信息

DataFrame的基础属性

  • df.shape #行数 列数
  • df.dtypes #列数据类型
  • df.ndim #数据维度
  • df.index #行索引
  • df.columns #列索引
  • df.values #对象值,二维ndarray数组

DataFrame整体情况查询

  • df.head(3) #显示头部几行,默认5行
  • df.tail(3) #显示末尾几行,默认5行
  • df.info() #相关信息概览:行数,列数,列索引,列非空值个数,列类型,内存占用
  • df.describe() #快速综合统计结果:计数,均值,标准差,最大值,四分位数,最小值
import pandas as pd

l = [{"name":"xiaoming","age":20,"tel":10086},{"name":"xiaohong","tel":10010},{"name":"xiaogang","age":18}]
df = pd.DataFrame(l)
print(df)

print("行索引:",df.index)
print("列索引:",df.columns)
print("值:",df.values)
print("形状:",df.shape)
print("列数据类型:",df.dtypes)
print("维度:",df.ndim)

print("显示前2行:")
print(df.head(2))
print("显示后两行:")
print(df.tail(2))
print("展示概览:")
print(df.info())
print("显示统计数据:")
print(df.describe())

在这里插入图片描述

  • 按照某一列进行排序: df.sort_values()

  • pandas取行或者列注意点:

    (1)方括号写数表示取行,对行进行操作

    (2)写字符串表示取列,对列进行操作

  • pandas中有许多优化过的选择方式:

    (1)df.loc 通过 标签 索引行数据

    (2)df.iloc通过 位置 索引行数据

    import pandas as pd
    import numpy as np
    
    t = pd.DataFrame(np.arange(12).reshape((3,4)),index=list("abc"),columns=list("WXYZ"))
    print(t)
    
    print(t.loc["a","Z"])
    print(type(t.loc["a","Z"]))
    print(t.loc["a":"c",["W","Z"]])#注意冒号在loc里面是闭合的,及会选中冒号后的数字
    
    print(t.iloc[1,:])
    

在这里插入图片描述

统计方法和字符串离散化
#要求对一组电影数据,呈现rating,runtime的分布情况
import pandas as pd
from matplotlib import pyplot as plt

file_path = "D:\jupyter_notebook\IMDB-Movie-Data.csv"
df = pd.read_csv(file_path)
#print(df.head(1))
#print(df.info())

#rating,runtime分布情况
#选择图形,直方图
#准备数据
runtime_data = df["Runtime (Minutes)"].values
max_runtime = runtime_data.max()
min_runtime = runtime_data.min()
#计算组数
num_bin = (max_runtime-min_runtime)//5
#设置图像大小
plt.figure(figsize=(20,8),dpi=80)
#绘制图像
plt.hist(runtime_data,num_bin,edgecolor="black")
#x轴刻度
plt.xticks(range(min_runtime,max_runtime+5,5))
#显示图像
plt.show()

在这里插入图片描述

#从一组电影数据中,知道评分的平均分和导演人数等信息
import pandas as pd


file_path = "D:\jupyter_notebook\IMDB-Movie-Data.csv"
df = pd.read_csv(file_path)

#获取电影平均评分
print("电影平均评分:",df["Rating"].mean())
print(len(set(df["Director"].tolist())))
print(len(df["Director"].unique()))
数据的合并和分组组合
#对于一组电影数据,统计电影分类情况
import pandas as pd
import numpy as np

file_path = "D:\jupyter_notebook\IMDB-Movie-Data.csv"
df = pd.read_csv(file_path)

#print(df["Genre"])
#统计分类的列表
temp_list = df["Genre"].str.split(",").tolist()
genre_list = list(set(i for j in temp_list for i in j))

#构造全为0的数组
zeros_df = pd.DataFrame(np.zeros((df.shape[0],len(genre_list))),columns=genre_list)
#给每个电影出现非农类的位置赋值1
for i in range(df.shape[0]):
    zeros_df.loc[i,temp_list[i]] = 1
#print(zeros_df.sum(axis = 0))

#排序
print(zeros_df.sum(axis=0).sort_values())

在这里插入图片描述

  • join方法:默认情况下把行索引相同的数据合并到一起

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XrCi4Sfe-1570932436065)(D:\typora\workspace\python中numpy、pandas、matplotlib的使用.assets\1570851351451.png)]

  • merge方法:把列索引相同的数据合并到一起
    在这里插入图片描述

  • pandas中分组操作:df.groupby(by = “columns_name”)

import pandas as pd
import numpy as np

file_path = "D:\jupyter_notebook\starbucks_store_worldwide.csv"
df = pd.read_csv(file_path)
#print(df.head(1))
#print(df.info())
grouped = df.groupby(by="Country")
print(grouped)#返回一个DataFrameGroupBy对象,可以遍历和聚合
print(grouped["Country"].count().loc[["US","CN"]])

#统计中国每一个省份星巴克的数量
china_data = df[df["Country"] == "CN"]
grouped = china_data.groupby(by = "State/Province").count()["Brand"]
print(grouped)

在这里插入图片描述

  • 索引和复合索引
    在这里插入图片描述
pandas中的时间序列
  • 生成一段时间范围: pd.date_range(start=None,end=None,periods=None,freq=‘D’)

    ​ #生成start和end范围内以freq频率的一组时间
    在这里插入图片描述
    在这里插入图片描述

  • 重采样:指的是将时间序列从一个频率转化为另一个频率进行处理的过程,将高频率数据转化为低频率数据为降采样,低频率转化为高频率为升采样,采用 pd.resample() 来实现
    在这里插入图片描述

matplotlib

matplotlib是最流行的python底层绘图库,主要做数据可视化图表

绘制折线图

首先让我们简单的绘制一个折线图

from matplotlib import pyplot as plt #导入pyplot
x = range(2,26,2) #数据在x轴的位置
y = [15,13,14.5,17,20,25,26,26,24,22,18,15] #数据在y轴的位置
plt.plot(x,y) #传入x和y,通过plot绘制出折线图
plt.show() #在执行程序时展示图形

在这里插入图片描述
现在我们来试着调节图片的大小

from matplotlib import pyplot as plt
fig = plt.figure(figsize = (20,8),dpi = 80)
'''宽20高8,图像模糊时可以传入dpi参数来使图像清晰'''
x = range(2,26,2)
y = [15,13,14.5,17,20,25,26,26,24,22,18,15] 
plt.plot(x,y) 
plt.show() 

然后我们想要将我们的折线图保存下来

from matplotlib import pyplot as plt
x = range(2,26,2)
y = [15,13,14.5,17,20,25,26,26,24,22,18,15] 
plt.plot(x,y) 
plt.savefig('./test.png')#在当前路径下保存为一个png文件
'''可以保存为svg这种矢量图格式,放大不会有锯齿'''
plt.show() 

在这里插入图片描述
如果我们想让x轴的刻度按照我么想要的来,那么我们需要设置x轴的刻度

from matplotlib import pyplot as plt
x = range(2,26,2)
y = [15,13,14.5,17,20,25,26,26,24,22,18,15] 
plt.plot(x,y) 
plt.xticks(x)#设置x轴的刻度
plt.show() 

我们现在再来一个例子,我们想要在坐标轴显示字符串

from matplotlib import pyplot as plt
import random

x = range(0,120)
y = [random.randint(20,35) for i in range(120)]

plt.figure(figsize = (20,8),dpi = 80)
plt.plot(x,y)

#调整x轴的刻度
_x = list(x)
_xtick_labels = ["10点{}分".format(i) for i in range(60)]
_xtick_labels += ["11点{}分".format(i) for i in range(60)]
plt.xticks(_x[::3],_xtick_labels[::3])

plt.show()#先让我们忽略中文乱码的问题

若想要旋转坐标轴

from matplotlib import pyplot as plt
import random

x = range(0,120)
y = [random.randint(20,35) for i in range(120)]

plt.figure(figsize = (20,8),dpi = 80)
plt.plot(x,y)

#调整x轴的刻度
_x = list(x)
_xtick_labels = ["10点{}分".format(i) for i in range(60)]
_xtick_labels += ["11点{}分".format(i) for i in range(60)]
plt.xticks(_x[::3],_xtick_labels[::3],rotation = 90)#ratation旋转的度数,默认按照逆时针

plt.show()#先让我们忽略中文乱码的问题

现在让我们显示中文

from matplotlib import pyplot as plt
import random

x = range(0,120)
y = [random.randint(20,35) for i in range(120)]

plt.figure(figsize = (20,8),dpi = 80)
plt.plot(x,y)

_x = list(x)
_xtick_labels = ["10点{}分".format(i) for i in range(60)]
_xtick_labels += ["11点{}分".format(i) for i in range(60)]
plt.xticks(_x[::3],_xtick_labels[::3],rotation = 90)

#这种方法仅适用于windows/linux
plt.rcParams['font.sans-serif'] = ['SimHei']  #步骤一(替换sans-serif字体)
#mac使用下面的代码
# plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
plt.rcParams['axes.unicode_minus'] = False  #步骤二(解决坐标轴负数的负号显示问题)

plt.show()

在这里插入图片描述
我们现在只是让我们想要的图显示了出来,但是别人并不知道我们图片到底代表什么,这就需要给我们的x轴、y轴添加描述信息,并添加表头,这次让我们彻底解决中文乱码的问题

from matplotlib import pyplot as plt
import random
import matplotlib.font_manager

my_font = font_manager.FontProperties(fname = "C:\Windows\Fonts")

x = range(0,120)
y = [random.randint(20,35) for i in range(120)]

plt.figure(figsize = (20,8),dpi = 80)
plt.plot(x,y)

_x = list(x)
_xtick_labels = ["10点{}分".format(i) for i in range(60)]
_xtick_labels += ["11点{}分".format(i) for i in range(60)]
plt.xticks(_x[::3],_xtick_labels[::3],rotation = 90)

#给坐标轴添加描述信息
plt.xlabel("时间")
plt.ylabel("温度 单位(℃)")
plt.title("10点到12点每分钟的气温变化情况")

plt.show()

在这里插入图片描述
如果我们想要在同一个图像中显示两个数据,并添加图例

from matplotlib import pyplot as plt

x = range(11,31)
y_1 = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
y_2 = [1,0,3,1,2,2,3,3,2,1,2,1,1,1,1,1,1,1,1,1]

plt.figure(figsize = (20,8),dpi = 80)

#参数color可以控制线条颜色,linestyle控制线条风格,linewidth控制线条粗细 
plt.plot(x,y_1,label = '自己')
plt.plot(x,y_2,label = '随便')

_xtick_labels = ["{}岁".format(i) for i in x]
plt.xticks(x,_xtick_labels)
plt.yticks(range(0,9))

plt.rcParams['font.sans-serif'] = ['SimHei']

plt.grid(alpha = 0.2)#设置网格并通过alpha参数控制网格的透明度

plt.legend()#添加图例

plt.show()

绘制散点图

散点图需要用到 **plt.scatter()**方法

from matplotlib import pyplot as plt

y_3 = [11,17,16,11,12,11,12,6,6,7,8,9,12,15,14,17,18,21,16,17,20,14,15,15,15,19,21,22,22,20,21]
y_10 = [26,2,28,29,21,17,16,19,18,20,20,19,22,23,17,20,21,20,22,15,11,15,5,13,17,18,11,15,14,12,11]

x_3 = range(1,32)
x_10 = range(51,82)

plt.figure(figsize = (20,8),dpi = 80)

plt.scatter(x_3,y_3,label = "3月份")
plt.scatter(x_10,y_10,label = "5月份")

_xtick_labels = ["3月{}号".format(i) for i in x_3]
_xtick_labels += ["10月{}号".format(i - 50) for i in x_10]
plt.xticks(list(x_3)+list(x_10),_xtick_labels,rotation = 90)

plt.rcParams['font.sans-serif'] = ['SimHei']

plt.xlabel("时间")
plt.ylabel("温度")
plt.title("标题")
plt.legend(loc = "upper left")

plt.show()

在这里插入图片描述

绘制条形图

from matplotlib import pyplot as plt
a = ["战狼2","速度与激情8","功夫瑜伽","西游伏妖篇","变形金刚5:最后的骑士","摔跤吧!爸爸","加勒比海盗5:死无对证","金刚:骷髅岛","极限特工:终极回归","生化危机6:终章","乘风破浪","神偷奶爸3","智取威虎山","大闹天竺","金刚狼3:殊死一战","蜘蛛侠:英雄归来","悟空传","银河护卫队2","情圣","新木乃伊"]

b = [56.01,26.94,17.53,16.49,15.45,12.96,11.8,11.61,11.28,11.12,10.49,10.3,8.75,7.55,7.32,6.99,6.88,6.86,6.58,6.23]
plt.figure(figsize = (20,8),dpi = 80)
plt.bar(range(len(a)),b)
plt.xticks(range(len(a)),a,rotation = 90)

plt.rcParams['font.sans-serif'] = ['SimHei']

plt.show()

在这里插入图片描述

#绘制横向条形图,采用plt.barh()
from matplotlib import pyplot as plt
a = ["战狼2","速度与激情8","功夫瑜伽","西游伏妖篇","变形金刚5:最后的骑士","摔跤吧!爸爸","加勒比海盗5:死无对证","金刚:骷髅岛","极限特工:终极回归","生化危机6:终章","乘风破浪","神偷奶爸3","智取威虎山","大闹天竺","金刚狼3:殊死一战","蜘蛛侠:英雄归来","悟空传","银河护卫队2","情圣","新木乃伊"]

b = [56.01,26.94,17.53,16.49,15.45,12.96,11.8,11.61,11.28,11.12,10.49,10.3,8.75,7.55,7.32,6.99,6.88,6.86,6.58,6.23]
plt.figure(figsize = (15,8),dpi = 80)
plt.barh(range(len(a)),b)
plt.yticks(range(len(a)),a)

plt.rcParams['font.sans-serif'] = ['SimHei']

plt.show()

在这里插入图片描述

#现在我们得到了多组数据,要把他们画在一张图上
from matplotlib import pyplot as plt
a = ["猩球崛起3:终极之战","敦刻尔克","蜘蛛侠:英雄归来","战狼2"]
b_14 = [2358,399,2358,362]
b_15 = [12357,156,2045,169]
b_16 = [15746,312,4497,319]

x_14 = list(range(len(a)))
x_15 = [i+0.2 for i in x_14]
x_16 = [i+0.2*2 for i in x_14]

plt.figure(figsize=(20,8),dpi = 80)
plt.bar(x_14,b_14,width=0.2,label = "9月14日")
plt.bar(x_15,b_15,width=0.2,label = "9月15日")
plt.bar(x_16,b_16,width=0.2,label = "9月16日")

plt.xticks(x_15,a)
plt.yticks(list(range(300,16000,1000)))
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.legend()

plt.show()

在这里插入图片描述

绘制直方图

采用 **plt.hist()**来实现直方图的绘制

import matplotlib.pyplot as plt
import numpy as np
import matplotlib

# 设置matplotlib正常显示中文和负号
matplotlib.rcParams['font.sans-serif']=['SimHei']   # 用黑体显示中文
matplotlib.rcParams['axes.unicode_minus']=False     # 正常显示负号
# 随机生成(10000,)服从正态分布的数据
data = np.random.randn(10000)
"""
绘制直方图
data:必选参数,绘图数据
bins:直方图的长条形数目,可选项,默认为10
facecolor:长条形的颜色
edgecolor:长条形边框的颜色
alpha:透明度
"""
plt.hist(data, bins=40, facecolor="blue", edgecolor="black", alpha=0.7)
# 显示横轴标签
plt.xlabel("区间")
# 显示纵轴标签
plt.ylabel("频数/频率")
# 显示图标题
plt.title("频数/频率分布直方图")
plt.show()

在这里插入图片描述

补充

  • plt.xlim()对x轴进行取值范围的限制;plt.ylim()对y轴进行取值范围的限制

  • plt.gca()可以去当前的图像状态

    ax = plt.gca()
    ax.spines['right'].setcolor('none')
    

案例

PM2.5

题目:现有北上广、深圳和沈阳5个城市空气质量数据,请绘制出5个城市的PM2.5随时间的变化情况

import pandas as pd
from matplotlib import pyplot as plt

file_path = "D:\jupyter_notebook\PM2.5\BeijingPM20100101_20151231.csv"
df = pd.read_csv(file_path)

#数据预览
#print(df.head(3))
#print(df.info())

#将时间连接起来
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
#print(df.head(10))

#把datetime设置为索引
df.set_index("datetime",inplace=True)

#进行降采样
df = df.resample("7D").mean()

#处理缺失数据,删除缺失数据
data = df["PM_US Post"].dropna()

#画图
_x = data.index
_y = data.values

plt.figure(figsize=(20,8),dpi = 80)

plt.plot(range(len(_x)),_y)

plt.xticks(range(0,len(_x),10),list(_x)[::10],rotation=45)

plt.show()

在这里插入图片描述

有北上广、深圳和沈阳5个城市空气质量数据,请绘制出5个城市的PM2.5随时间的变化情况

import pandas as pd
from matplotlib import pyplot as plt

file_path = "D:\jupyter_notebook\PM2.5\BeijingPM20100101_20151231.csv"
df = pd.read_csv(file_path)

#数据预览
#print(df.head(3))
#print(df.info())

#将时间连接起来
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
#print(df.head(10))

#把datetime设置为索引
df.set_index("datetime",inplace=True)

#进行降采样
df = df.resample("7D").mean()

#处理缺失数据,删除缺失数据
data = df["PM_US Post"].dropna()

#画图
_x = data.index
_y = data.values

plt.figure(figsize=(20,8),dpi = 80)

plt.plot(range(len(_x)),_y)

plt.xticks(range(0,len(_x),10),list(_x)[::10],rotation=45)

plt.show()

[外链图片转存中…(img-r5z8s1vq-1570932436089)]

  • 13
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值