pandaa&&numpy学习笔记


numpy,matplotlib,pandas以及文件批量操作

写在前面,由于自己python基础能力有点菜,并且基本上每上手一个框架都需要这四方面的操作以及掌握,所以我决定恶补这方面的不足,故有了这样一篇博客,持续更新中~

  • 环境:conda,jupyter notebook

matplotlib

绘图用库,进行数据可视化,

练手项目1 初识matplotlib,绘制折线图

教学部分

假设一天中每隔两个小时(range(2,26,2))的气温分别是:

[15,13,14,5,17,20,25,26,27,22,18,15]

from matplotlib import pyplot as plt
#导入pyplot模块
x = range(2, 26, 2)#设置x轴的步距以及上下限
y = [15, 13, 14, 5, 17, 20, 25, 26, 27, 22, 18, 15]#y轴的数据,和x对应
plt.plot(x, y)#执行方法
plt.show()#show方法
#最后画出一个折线图

要点:x和y的数据量一定要一一对应,不然会直接报错,要求步长和上下限list的数据大小和y中一样

但是这样生成的图表示的数据很模糊,没有标注以及并不好看

目前存在以下几个问题:

  • 设置图片大小
  • 保存到本地
  • 描述信息,比如x轴和y轴表示什么,这个图表示什么
  • 描述x或者y的刻度的间距
  • 标记出特殊点的(比如最高以及最低点)
  • 给图片添加一个水印(防伪)

设置图片大小/保存图片:

from matplotlib import pyplot as plt

fig = plt.figure(figsize=(20, 8), dpi=80)
# figure图形图标的意思,这里指的是我们画的图,通过实例化一个figure并且传递参数,能够在后台自动使用该figure实例
# dpi参数,让图片更加清楚
x = range(2, 26, 2)
y = [15, 13, 14.5, 17, 20, 25, 26, 26, 27, 22, 18, 15]
plt.plot(x, y)
# 或者这种方法_xtick_labels=[i/2 for i in range(2,50)]
# plt.xticks(_xtick_labels)采用传入数组的方法式
# plt.yticks(range(min(y),max(y)+1))步距自动为1
plt.xticks(range(2, 25))  # 设置x轴显示步距
plt.yticks(range(10, 30, 1))  # range,(start ,end,step)
plt.savefig("./first.png")  # 在本地保存
plt.show()

项目

内容

如果a表示10到12点的每一分钟的气温,如何绘制折线观察每分钟的气温变化

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

from matplotlib import pyplot as plt
import random as rd
#记得导入随机数库
a = [rd.randint(20, 35) for i in range(120)]#设置x,y轴
x = range(1, 121)
plt.plot(x, a)#实例化图形
plt.xticks(range(1, 121))
plt.yticks(range(15, 41))#设置xy轴参数
plt.show()#显示
plt.savefig("./firstproject.png")#保存

现在这个代码有点问题,问题在于x轴并不能如实反映钟点数,而是10进制

转化成时间形式

修改后

from matplotlib import pyplot as plt
import random as rd

a = [rd.randint(20, 35) for i in range(120)]
x = range(1, 121)
plt.figure(figsize=(20,8),dpi=80)#修改长宽比,修改像素 这是决定图片好看与否的一个因素
plt.plot(x, a)
_x = list(x)[::3]  # 修改步长变成3,要修改成列表形式 
_xtick_label = ["10:{}".format(i) for i in range(60)]
_xtick_label += ["11:{}".format(i) for i in range(60)]  # 追加列表尾
plt.xticks(_x, _xtick_label[::3],rotation=300)  # rotation旋转的度数
#前两个参数数量大小应该一样,则不能完全覆盖整个轴
#第一个参数:上下限,是个列表,第二个参数吗,同样是个列表,表示参数注释,注释基本上没有中文
plt.yticks(range(15, 41))
plt.show()
plt.savefig("./firstproject.png")
显示中文以及修改设置

在pycharm中,ctrol加上鼠标可查看模块源码

比如修改matplotlib的绘图设置,可以

import matplotlib
matplotlib.rc

然后点开源码,进行查看

 """
    Set the current `.rcParams`.  *group* is the grouping for the rc, e.g.,
    for ``lines.linewidth`` the group is ``lines``, for
    ``axes.facecolor``, the group is ``axes``, and so on.  Group may
    also be a list or tuple of group names, e.g., (*xtick*, *ytick*).
    *kwargs* is a dictionary attribute name/value pairs, e.g.,::

      rc('lines', linewidth=2, color='r')可以设置线条样式

    sets the current `.rcParams` and is equivalent to::

      rcParams['lines.linewidth'] = 2
      rcParams['lines.color'] = 'r'

    The following aliases are available to save typing for interactive users:

    =====   =================
    Alias   Property
    =====   =================
    'lw'    'linewidth'
    'ls'    'linestyle'
    'c'     'color'
    'fc'    'facecolor'
    'ec'    'edgecolor'
    'mew'   'markeredgewidth'
    'aa'    'antialiased'
    =====   =================

    Thus you could abbreviate the above call as::

          rc('lines', lw=2, c='r')

    Note you can use python's kwargs dictionary facility to store
    dictionaries of default parameters.  e.g., you can customize the
    font rc as follows::

      font = {'family' : 'monospace',或者这种字典写法,引入后一一对应
              'weight' : 'bold',
              'size'   : 'larger'}
      rc('font', **font)  # pass in the font dict as kwargs

    This enables you to easily switch between several configurations.  Use
    ``matplotlib.style.use('default')`` or :func:`~matplotlib.rcdefaults` to
    restore the default `.rcParams` after changes.

    Notes
    -----
    Similar functionality is available by using the normal dict interface, i.e.
    ``rcParams.update({"lines.linewidth": 2, ...})`` (but ``rcParams.update``
    does not support abbreviations or grouping).
    """

则可以

import matplotlib
font = {'family' : 'monospace'
              'weight' : 'bold',
              'size'   : 'larger'}
matplotlib.rc('font', **font)

或者通过此显示中文

from matplotlib import font_manager
my_font=font_manager.FontProperties(fname="C:\Windows\Fonts\PingFang.ttc")
#字体所在地址

具体中文显示可以见此博客

使用matplotlib绘图时中文字体的解决方案

给图添加描述信息
plt.xlabel("Time")
plt.ylabel("temperaturec")
#x与y轴分别标注
plt.title("10:00-12:00")
#给图添加标题

总结:

  • 学习了怎么绘图:

    • from matplotlib import pyplot as plt
    • plt.plot(x,y)
    • plt.show()

    这三个是绘图的主要流程,即调库,导入数据,显示

  • 对图形进行优化

    • plt.figure(长宽比,像素)
    • _xtick_label实例化一个列表后,作为参数导入plt.xticks()方法,从而对x轴进行优化、
    • plt.xlabel()和plt.ylabel()解释参数plt.title()给图片命名
    • 保存图片plt.savefig()
    • 字体设置,详见博客

课后作业

课后作业

代码如下

from matplotlib import pyplot as plt

x = [i for i in range(11,31)]
y = [1, 0, 1, 1, 2, 4, 3, 2, 3, 4, 4, 5, 6, 5, 4, 3, 3, 1, 1, 1]
plt.figure(figsize=(20, 8), dpi=80)
plt.plot(x, y)
plt.xlabel("age")
plt.ylabel("the number of girl(boy) friends")
plt.title("my plot")
_x = list(x)
x_label= ["{}year".format(i) for i in range(11,31)]
y_label = ["{} boys or girls".format(i) for i in y]
plt.xticks(_x,x_label,rotation=300)
plt.yticks(range(0,9))#注意名字不能写错,
plt.show()

练手项目2 绘制散点图和折线图

绘制散点图

假设通过爬虫你获取到了北京2016年3,10月份每天白天的最高气温(分别位于列表a,b),那么此时如何寻找出气温和随时间(天)变化的某种规律?

a =[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,22,23]

b =[26,26,28,19,21,17,16,19,18,20,20,19,22,23,17,20,21,20,22,15,11,15,5,13,17,10,11,13,12,13,6]

三月单独绘制代码如下:

from matplotlib import pyplot as plt
from matplotlib import font_manager

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, 22,
     23]
y_10 = [26, 26, 28, 19, 21, 17, 16, 19, 18, 20, 20, 19, 22, 23, 17, 20, 21, 20, 22, 15, 11, 15, 5, 13, 17, 10, 11, 13, 12,
     13, 6]
x=range(1,32)
plt.scatter(x,y_3)
plt.show()

但是这时并没有达到我们想要的结果,我们想要绘制一个三月十月同时存在的图,并且有完整图例

from matplotlib import pyplot as plt
from matplotlib import font_manager
myfont=font_manager.FontProperties(fname="C:\Windows\Fonts\STKAITI.TTF")
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,
       22,
       23]
y_10 = [26, 26, 28, 19, 21, 17, 16, 19, 18, 20, 20, 19, 22, 23, 17, 20, 21, 20, 22, 15, 11, 15, 5, 13, 17, 10, 11, 13,
        12,
        13, 6]
x_3 = range(1, 32)
x_10 = range(51, 82)
plt.figure(figsize=(20, 8), dpi=120)
#与绘制折线图唯一的区别
plt.scatter(x_3, y_3,label="三月份")
plt.scatter(x_10, y_10,label="十月份")

_x = list(x_3) + list(x_10)
_xticks_labels = ["三月{}日".format(i) for i in x_3]
_xticks_labels += ["十月{}日".format(i - 50) for i in x_10]
plt.legend(loc="upper left",prop=myfont)#添加图例

plt.xticks(_x[::3], _xticks_labels[::3],fontProperties=myfont, rotation=300)
plt.ylabel("气温C",fontProperties=myfont)
plt.title("气温对照表",fontProperties=myfont)
plt.show()

之后会利用散点图绘制线性回归的拟合曲线

绘制条形图

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]单位:亿

代码如下

from matplotlib import pyplot as plt
from matplotlib import font_manager
myfont=font_manager.FontProperties(fname="C:\Windows\Fonts\STKAITI.TTF")
a = ["战狼2","速度与激情8", "功夫瑜伽","西游伏妖篇","变形金刚5∶最后的骑士","摔跤吧!爸爸" ]
b = [56.01,26.94,17.53,16.49,15.45,12.96]
plt.figure(figsize=(20, 8), dpi=120)
#与绘制折线图唯一的区别

plt.bar(range(len(a)),b,width=0.3)

plt.xticks(range(len(a)),a,fontProperties=myfont, rotation=300)
plt.show()

截断了前6个

但是我们更加希望是变成竖着的条形图,那么就改成barh,于是代码如下

from matplotlib import pyplot as plt
from matplotlib import font_manager
myfont=font_manager.FontProperties(fname="C:\Windows\Fonts\STKAITI.TTF")
a = ["战狼2","速度与激情8", "功夫瑜伽","西游伏妖篇","变形金刚5∶最后的骑士","摔跤吧!爸爸" ]
b = [56.01,26.94,17.53,16.49,15.45,12.96]
plt.figure(figsize=(20, 8), dpi=120)
#与绘制折线图唯一的区别

plt.barh(range(len(a)),b,height=0.3,color="red")
#改成竖图后,wight应该改成hight
plt.yticks(range(len(a)),a,fontProperties=myfont)
plt.grid(alpha=0.3)#设置网格
plt.show()

课后练习

假设你知道了列表a中电影分别在2017-09-14(b_ 14), 2017-09 -15(b _15),2017-09-16(b _16)三天的票房,为了展示列表中电影本身的票房以及同其他假设你知道了列表a中电影分别在2017-09- -14(b14), 2017-09 -15(b15),
2017-09- 16(b16)三天的票房,为了展示列表中电影本身的票房以及同其他电影的数据对比情况,应该如何更加直观的呈现该数据?
a= [“猩球崛起3:终极之战”,”敦刻尔克”,”蜘蛛侠:英雄归来”,”战狼2”]
b16 = [15746,312,4497,319]
b15 = [12357,156,2045,168]
b14 = [2358,399,2358,362]

代码如下

from matplotlib import pyplot as plt
from matplotlib import font_manager
myfont=font_manager.FontProperties(fname="C:\Windows\Fonts\STKAITI.TTF")
a= ["猩球崛起3:终极之战","敦刻尔克","蜘蛛侠:英雄归来","战狼2"]
b16 = [15746,312,4497,319]
b15 = [12357,156,2045,168]
b14 = [2358,399,2358,362]
plt.figure(figsize=(20, 8), dpi=120)
#与绘制折线图唯一的区别
x_14=list(range(len(a)))
x_15=[i+0.2 for i in x_14]
x_16=[i+0.4 for i in x_14]

plt.bar(range(len(a)),b14,width=0.2,color="red",label="九月14")
plt.bar(x_15,b15,width=0.2,color="orange",label="九月15")
plt.bar(x_16,b16,width=0.2,color="blue",label="九月16")
#改成竖图后,wight应该改成hight
plt.legend(prop=myfont)
plt.xticks(range(len(a)),a,fontProperties=myfont)
plt.grid(alpha=0.3)#设置网格
plt.show()

暂时的matplotlib到这,更多用法查询csdn

其他绘图工具推荐

echart:一个前端js框架

plotly:一个github上的项目,比matplotlib好看

numpy

创建numpy数组

import numpy as np
t1=np.array([1,2,3])
print(t1)
print(type(t1))
#[1 2 3]
#<class 'numpy.ndarray'>

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

t3 = np.arange(10)
print(t3)
#效果一样
#[0 1 2 3 4 5 6 7 8 9]

print(t3.dtype)
#int32

t3.dtype=float
print(t3.dtype)
#float64

t4=np.array([rd.random() for i in range(10)])
print(t4)
print(t4.dtype)

#[0.06217892 0.51319594 0.84344407 0.14711661 0.03576193 0.48263391
#0.79937126 0.49026005 0.43495258 0.8738894 ]
#float64

print(np.round(t4,2))
print(t4.dtype)#取两位
#[0.99 0.76 0.46 0.78 0.32 0.33 0.   0.56 0.89 0.66]
#float64

numpy数组操作

改变形状

import numpy as np
import random as rd
t1=np.arange(12)
print(t1.shape)
t2=np.array([[1,2,3],[3,4,5]])
print(t2.shape)
#查看形状

#修改形状
t3=np.arange(12)
t4=t3.reshape((3,4))
print(t4)
#改变形状,注意这里改变形状不对原数组进行改变,原地操作

注意这里的shape

(24,)与(24,1)是不一样的,前者的1个24行向量,后者是24个1列向量

以下是操作:

  • t.shape[0] t.shape[1]分别是行数和列数
  • t.flatten()数组降维一维

计算

nan:不是一个数字

INF:无穷

  • 点加减: t1+2
  • 点乘除:t1*2
  • 矩阵相加减:t1+t2(若不符合矩阵运算,某一维度相同时可以计算,效果类似点加减,广播原则)
  • 矩阵相乘除:t1*t2(以上要符合矩阵运算规律)

具体查csdn

numpy读取文件

现在这里有一个英国和美国各自youtube1000多个视频的点击,喜欢,不喜欢,评论数量([“views”,”likes” , “dislikes”,” comment total”])的csv,运用刚刚所学习的只是,我们尝试来对其进行操作

数据来源

切片索引操作

见blog

numpy切片索引操作

或者bilibili视频

数据拼接

数组拼接

好的参考blog

blog1

blog2

小练习


文章作者: 晓沐
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 晓沐 !
评论
 上一篇
机器学习之sklearn 机器学习之sklearn
机器学习笔记之sklearn sklearn是机器学习中重要的测试数据集来源之一,并且可以提供特征提取以及降维聚类等功能 蒟蒻从今天起开始机器学习调库调参的第一步, sklearn数据集介绍引入:数据集的操作有: load_*获取
下一篇 
matlab基础使用(更新中) matlab基础使用(更新中)
Matlab基础使用写在前面和之前那篇不同的是,这篇文章记录了matlab基础使用的方法,总共也就那么几个部分 向量运算 多项式运算 矩阵运算 符号运算 数列求和与函数极限与导数操作 函数积分 方程求解 微分方程//曲线方程 拟合插值(这
2020-08-15
  目录