numpy模块

用来数据分析,对numpy数组(矩阵)

import numpy as np

arr1 = np.array([1,2,3])
arr2 = np.array([4,5,6])
print(arr1 * arr2)  # [4,10,18]

二维数组

arr = np.array([
    [1,2,3],
    [4,5,6]
])  

numpy数组的属性

T 数组的装置

print(arr.T)  # 对高维数组而言,行列互换,转置

dtype 数组元素的数据类型

numpy数组是属于python解释器(int32/float64)

print(arr.dtype)

size 数组元素的个数

print(arr.size)  # 6

ndim 数组的维数

print(arr.ndim)  # 2

shape数组的维度大小

print(arr.shape())  # (2,3) 行,列

astype 类型转换

arr = arr.astype(np.float64)
print(arr)  

切片

print(arr[:,:])  # 行,列

print(arr[0,0])  # 1

print(arr[0.:])  # 第一行所有元素

print(arr[:,-2:])  # 最后两列元素

print(arr[arr>4])  # 大于4的元素

赋值

arr[0,0] = 0  # 第1行第1列元素为0

arr[0,:] = 0  # 第一行元素都为0

arr[:,:] = 0  # 所有元素均为0

数组的合并

arr1 = np.array([
    [1, 2, 3],
    [4, 5, 6]
])

arr2 = np.array([
    [7, 8, 9],
    ['a', 'b', 'c']
])

print(np.hstack((arr1,arr2)))  # 按行合并(只能放元组)

print(np.vstack((arr1,arr2)))  # 按列合并

prtin(np.concatenate((arr1,arr2),axis = 1))  # 默认按列合并,0表示列,1表示行

通过函数创建numpy数组

print(np.ones((2,3)))  # 创建一个2行3列元素均为1的数组(只能放元组)

print(np.zeros((2,3)))  # 创建一个2行3列元素均为0的数组

print(np.eye(3,3))  # 创建一个n行n列均为1,其他元素为0的数组

print(np.linspace(1,100,10))  # 创建一个间隔(100-1)/(10-1)的从1到100的数组

print(np.arange(2,10))  # 创建2-9的数组(顾头不顾尾)

arr1 = np.zeros((1,12))
print(arr1.reshape((3,4)))  # 重构成3行4列的数组

numpy数组运算

# =-*/ // ** %
arr1 = np.ones((3,4)) * 4
print(arr1)

# sin
print(np.sin(arr1))  

# 矩阵运算(点乘)
arr1 = np.array([
    [1,2,3],
    [4,5,6]
])

arr2 = np.array([
    [1, 2],
    [4, 5],
    [6, 7]
])

print(np.dot(arr1, arr2))  # 2* 3 3*2

# 求逆
arr = np.array([[1, 2, 3], [4, 5, 6], [9, 8, 9]])
print(np.linalg.inv(arr))

# numpy数组数学和统计方法
print(np.sum(arr[0, :]))

numpy.random生成随机数

print(np.random.rand(3, 4))  #产生均匀分布的随机数

print(np.random.randn(3, 4))  #产生标准正态分布随机数

print(np.random.random((3, 4)))

np.random.seed(1)  # 固定随机数

rs = np.random.RandomState(1)  # 固定随机数
print(rs.rand(10))

arr = np.array([[1, 2, 3], [4, 5, 6], [9, 8, 9]])
np.random.shuffle(arr)
print(arr)  # 打乱顺序

print(np.random.randint(1, 100, (3, 4)))  # 针对某一个范围

matplotlib模块

条形图bar

from matplotlib import pyplot as plt

# 导入字体格式
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='C:\Windows\Fonts\simsun.ttc')   # 通过FontProperties中的关键字fname把字体格式传入到font

# 原数据
clas = ['3班', '4班', '5班', '6班']
students = [50, 55, 45, 60]

# 设置背景模板
plt.style.use('ggplot')

#range索引x轴的柱数
clas_index = range(len(clas))

# 通过bar画出柱状图,设置颜色
plt.bar(clas_index,students, color = 'darkblue')

# 通过xlabel\ylabel\title设置x轴\y轴标题和主标题
plt.xlabel('班级',fontproperties=font)
plt.ylabel('人数',fontproperties=font)
plt.title('班级-人数',fontproperties=font)

# 通过xticks将x轴索引柱数替换成clas,并设置字体格式
plt.xticks(clas_index, clas, fontproperties=font)

# 通过show将图标展示
plt.show()

直方图hist

from matplotlib import pyplot as plt
import numpy as np

#从matplotlib.font_manager导入字体
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='C:\Windows\Fonts\simsun.ttc')  # 通过FontProperties中的关键字fname把字体格式传入到font

# 通过style.use设置背景模板
plt.style.use('ggplot')

# 利用numpy/random/randn生成数据
x1 = np.random.randn(10000)  # 标准正态分布随机数
x2 = np.random.rand(10000)

# 通过figure生成画布, 再通过add_subplot控制生成画板的个数
fig = plt.figure()  # 生成画布
ax1 = fig.add_subplot(1,2,1)  # 分成1行2列的画板取第一个
ax2 = fig.add_subplot(1,2,2)  # 分成1行2列的画板取第二个

# 利用numpy/random/randn生成数据
x1 = np.random.randn(10000)  # 标准正态分布随机数
x2 = np.random.randn(10000)

# # 设置画板的调用数据\背景颜色
ax1.hist(x1,bins = 50, color = 'darkblue')  # bins=50表示每个变量的值分成50份,即会有50根柱子
ax2.hist(x2,bins = 50, color = 'y')

# 通过suptitle设置总标题
fig.suptitle('两个正太分布',fontproperties =font,fontsize = 20)

#通过set_title设置两个分标题
ax1.set_title('x1的正态分布',fontproperties = font)
ax2.set_title('x2的正态分布',fontproperties = font)

# 通过show展示出来
plt.show()

折线图plot

import numpy as np

#导入matplotlib中的pyplot功能
from matplotlib import pyplot as plt  # 导入matplotlib中的pyplot
from matplotlib.font_manager import  FontProperties  # 通过.font_manager导入FontProperties

# 通过FontProperties(fname = )导入字体
font = FontProperties(fname= 'C:\Windows\Fonts\simsun.ttc')
# 设置背景模板(style.use)
plt.style.use('ggplot')

# 通过numpy模块生成数据
np.random.seed(1)
x1 = np.random.randn(40).cumsum()  # 累加
x2 = np.random.randn(40).cumsum()  # 累加
x3 = np.random.randn(40).cumsum()  # 累加
x4 = np.random.randn(40).cumsum()  # 累加

# 通过plot画出折点图,linestyle线的类型(-/--/-./:), marker点的形状(o/*/s)
plt.plot(x1,c = 'r', linestyle = '-',marker = 'o', label = '红圆线')  # 红色,实线,圆点
plt.plot(x2,c = 'b', linestyle = '--',marker = '*', label = '蓝星线')  # 蓝色,虚线,星点
plt.plot(x3,c = 'y', linestyle = '-.',marker = 's', label = '黄方线')  # 黄色,实点线,方点
plt.plot(x4,c = 'black', linestyle = ':',marker = 's', label = '黑方线')  # 黑色,点线,方点

# 通过legend设置说明
plt.legend(loc = 'best',prop = font)

# 展示(show)
plt.show()

散点图scatter+直线图plot

import  numpy as np

# 导入模块(pyplot) 字体(.font_manager导入FontProperties)
from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties

font = FontProperties(fname = 'C:\Windows\Fonts\simsun.ttc')

# 模板(style.use)
plt.style.use('ggplot')

# 分画布(figure)
fig = plt.figure()
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)

#生成数据(arange)
x = np.arange(20)
y = x**2

x2 = np.arange(20)
y2 = x2

# 折点图
ax1.scatter(x,y,c = 'r',label = '红')
ax1.scatter(x2,y2,c = 'y',label = '黄')

# 直线图
ax2.plot(x,y)
ax2.plot(x2,y2)

# 添加标题
fig.suptitle('两张图', fontproperties=font, fontsize=15)
ax1.set_title('散点图', fontproperties = font)
ax2.set_title('折线图', fontproperties = font)
# 展示show
plt.show()

pandas模块

操作excel/json/sqlini/csv

import numpy as np
import pandas as pd

np.random.seed(1)

index = pd.date_range('2019-01-01',periods= 6, freq= 'M')
print(index)
columns = ['c1', 'c2', 'c3', 'c4']
print(columns)
data = np.random.randn(6, 4)
print(data)

# .DataFrame生成dataframe数据结构
df = pd.DataFrame(index=index, columns=columns,data =data)
print(df)

# to_excell保存文件,读出成文件
df.to_excel('data.xlsx')

# 读出文件
df = pd.read_excel('data.xlsx',index_col=[0])
print(df)

print(df.index)
print(df.columns)
print(df.values)

print(df[['c1', 'c2']])

# 按照index取值
print(df.loc['2019-01-31'])
print(df.loc['2019-01-31':'2019-05-31'])

# 按照values取值
print(df)
print(df.iloc[0,0])

df.iloc[0, :] = 0
print(df)

numpy+pandas+ matplotlib模块(day18)的更多相关文章

  1. 11-2 numpy/pandas/matplotlib模块

    目录 numpy模块 一维数组 二维数组 列表list和numpy的区别 获取多维数组的行和列 多维数组的索引 高级功能 多维数组的合并 通过函数方法创建多维数组 矩阵的运算 求最大值最小值 nump ...

  2. python 数据分析工具之 numpy pandas matplotlib

    作为一个网络技术人员,机器学习是一种很有必要学习的技术,在这个数据爆炸的时代更是如此. python做数据分析,最常用以下几个库 numpy pandas matplotlib 一.Numpy库 为了 ...

  3. 第一章:AI人工智能 の 数据预处理编程实战 Numpy, Pandas, Matplotlib, Scikit-Learn

    本课主题 数据中 Independent 变量和 Dependent 变量 Python 数据预处理的三大神器:Numpy.Pandas.Matplotlib Scikit-Learn 的机器学习实战 ...

  4. 常用统计分析python包开源学习代码 numpy pandas matplotlib

    常用统计分析python包开源学习代码 numpy pandas matplotlib 待办 https://github.com/zmzhouXJTU/Python-Data-Analysis

  5. Python模块简介及安装 [numpy,pandas,matplotlib,scipy,statsmodels,Gensim,sklearn,keras]

    https://pan.baidu.com/s/1bpVv3Ef  67bd          模块安装文件下载地址 pip install "numpy-1.12.0b+mkl-cp35- ...

  6. numpy, pandas, matplotlib等常用库的学习手册

    pandas介绍: 待续 参考资料: 中文:https://www.cnblogs.com/skying555/p/5914391.html 英文:http://www.datadependence. ...

  7. Ipython自动导入Numpy,pandas等模块

    一.引言 最近在学习numpy,书上要求安装一个Ipythpn,可以自动导入Numpy,pandas等数据分析的模块,可是当我安装后,并不能自动导入numpy模块,还需要自己import.我就去查了一 ...

  8. numpy+pandas+matplotlib+tushare股票分析

    一.数据导入 安装tushare模块包 pip install tushare http://tushare.org/ tushare是一个财经数据接口包 import numpy as np imp ...

  9. numpy pandas matplotlib

    import numpy as np import pandas as pd import matplotlib.pyplot as plt ---------------numpy--------- ...

随机推荐

  1. 读《深入理解Elasticsearch》点滴-查询分类

    1.如何分类,略.个人不接受书中的分类方法,建议采用官网上的分类方法 2.term查询,可以模拟No-SQL数据库

  2. c# 9.0 特性提案 简化空参数验证代码

    简而言之就是将已存在的特性null参数验证,使用一个简单的语义标注进一步简化. 对于如下这段代码 // Before void Insert(string s) { if (s is null) { ...

  3. 从github下载的vue项目启动宝Cannot Get错误

    从github下载的vue项目启动宝Cannot Get错误,网上参考出现该错误来源很多,这里先总结遇到的第一个解决方法. 参考地址: https://www.cnblogs.com/anns/p/7 ...

  4. Java初中级面试笔记及对应视频讲解

    笔试题链接:点击打开链接   密码:提取码:7h9e 视频下载链接: 点击打开链接  提取码:hyye 百万it课程 https://pan.baidu.com/s/1ldJ_Ak7y0VL5Xmy9 ...

  5. 58同城AES签名接口分析

    背景:需要获取58同城上面发布的职位信息,其中的包括职位的招聘要求,薪资福利,公司的信息,招聘者的联系方式.(中级爬虫的难度系数) 职位详情页分析 某个职位详情页的链接 https://qy.m.58 ...

  6. 手把手带你利用Ribbon实现客户端的负载均衡

    之前的文章<SpringCloud搭建注册中心与服务注册>介绍了注册中心的搭建和服务的注册,本文将介绍下服务消费者通过Ribbon调用服务实现负载均衡的过程. 本文目录 一.Ribbon服 ...

  7. 安装Office Visio 提示Office 16 Click-to-Run Extensibility Component

    今天在安装 Office Visio 2016 时,点击安装程序,出现以下错误:   出现这个问题的原因就是你的电脑以前安装过32位的office,卸载时,注册表没有清理干净. 解决方案: 在win1 ...

  8. Zabbix监控方案-官方最新4.4版本

    Zabbix 2019/10/12 Chenxin 参考 https://www.zabbix.com/documentation/4.0/zh/manual https://baike.baidu. ...

  9. django的url分发封装

    h2, body>h3, body>h4, body>h1{ padding: 10px; background-color: #4cae4c; text-align: center ...

  10. 纯C语言写的按键驱动,将按键逻辑与按键处理事件分离~

    button drive 杰杰自己写的一个按键驱动,支持单双击.连按.长按:采用回调处理按键事件(自定义消抖时间),使用只需3步,创建按键,按键事件与回调处理函数链接映射,周期检查按键. 源码地址:h ...