numpy 模块

numpy 模块主要用来做数据分析,对numpy数组 进行科学运算

主要方法和常用属性,都是用numpy 生成的对象.出来的

import numpy as np

属性 描述
T 数组的转置,行和列一一对应,重构,每行2个元素
dtype 数组元素的数据类型(int32 和 float64)
size 数组元素的个数
ndim 数组的维数
shape 数组的维度大小(有几行几列)
astype 数据类型转换
常用方法 描述
元素切分 [:,:] 表示行和列
逻辑取值 取出用numpy生成的数组对象 > 4的元素
赋值 取出用numpy生成的数组对象的索引值 = 0
数组横向合并 行和行合并,列和列合并
数组垂直合并 相当于list update,直接添加元素
数组函数 描述
np.array() 将列表转换为数组,可选择是否制定dtype
np.ones() 传入行数和列数,值都为1
np.zeros() 传入行数和列数,值都为0
np.eye() 输入行数和列数,对角值为1
np.arange() 和列表的range方法一样,支持浮点数
np.linspace() 类似arange(),第三个参数为数组长度
np.empty() 创建一个元素全随机的数组
np.reshape() 重塑形状
数组运算 与数组函数联用 +-*/ 数字
生成随机数(常用) np.random.rand(x,y)
np.random.random(x,y)
np.random.choice(x,y)
np.random.shuffle(x,y)
numpy数学 统计方法 描述
sum 求和
cumsum 累加求和
mean 求平均数
std 求标准差
var 求方差
min 求最小值
max 求最大值
argmin 求最小值索引
argmax 求最大值索引
sort 排序

以下代码具体解释

lt1 = [1,2,3]
lt2 = [4,5,6] lt = []
# 如果我们想要对这两个列表内数据相乘,我们可以用for循环
for i in range(len(lt1)):
lt.append(lt1[i] * lt2[i])
print(lt) import numpy as np # 利用numpy 进行矩阵计算 更方便
arr1 = np.array([1,2,3])
arr2 = np.array([4,5,6])
print(arr1 * arr2)
## [ 4 10 18] # numpy 创建 numpy 数组 --》 可变的数据类型
# 一维数组 通常不使用,创建的数组没有,
arr = np.array([1,2,3])
print(arr)
# [1 2 3] # 二维数组
arr = np.array([
[1,2,3],
[4,5,6]
])
print(arr)
# [[1 2 3]
# [4 5 6]] # 三维数组 通常不使用
arr = np.array([
[1,2,3],
[4,5,6],
[7,8,9]
])
print(arr)
# [[1 2 3]
# [4 5 6]
# [7 8 9]] # numpy 数组的属性 特性
arr = np.array([
[1,2,3],
[4,5,6]
]) # T数组的转置,行列互换
print(arr, "\n",arr.T)
# [[1 4]
# [2 5]
# [3 6]] # dtype 数组元素的数据类型,
# numpy数组是属于python解释器的,
# int32 float64 属于numpy数组
print(arr.dtype)
# int32 # size 数组元素的个数
print(arr.size)
# 6 # ndim 数据的维数
print(arr.ndim)
# 2 # shape 数据的纬度大小(以元组形式)
print(arr.shape)
# (2, 3) # astype 类型转换 为int32
arr = arr.astype(np.float64)
print(arr)
# [[1. 2. 3.]
# [4. 5. 6.]] # 切片numpy数组
arr = np.array([
[1, 2, 3],
[4, 5, 6]
]) print(arr[:,:]) # :行,:列
# [[1 2 3]
# [4 5 6]]
print(arr[0,0])
# 1
print(arr[1,2])
# 6
print(arr[:,-2:])
# [[2 3]
# [5 6]] # 逻辑取值
print(arr[arr > 4])
# [[2 3]
# [5 6]]
# [5 6] # 赋值
arr[0,0] = 0
print(arr)
# [[0 2 3]
# [4 5 6]] # 数组合并
arr1 = np.array([
[1, 2, 3],
[4, 5, 6]
]) arr2 = np.array([
[7, 8, 9],
['a', 'b', 'c']
]) # 横向合并
print(np.hstack((arr1,arr2)))
# [['1' '2' '3' '7' '8' '9']
# ['4' '5' '6' 'a' 'b' 'c']] # 垂直合并
print(np.vstack((arr1,arr2)))
# [['1' '2' '3']
# ['4' '5' '6']
# ['7' '8' '9']
# ['a' 'b' 'c']] # 默认以列合并 #axis = 0 0表示列,1表示行
print(np.concatenate((arr1,arr2),axis=1))
# [['1' '2' '3' '7' '8' '9']
# ['4' '5' '6' 'a' 'b' 'c']] # 通过函数创建numpy数组 print(np.ones((2,3)))
# [[1. 1. 1.]
# [1. 1. 1.]] print(np.zeros((2,3)))
# [[0. 0. 0.]
# [0. 0. 0.]] print(np.eye(3,3))
# [0. 1. 0.]
# [0. 0. 1.]] print(np.linspace(1,100,10))
# [ 1. 12. 23. 34. 45. 56. 67. 78. 89. 100.] print(np.arange(2,10))
# [2 3 4 5 6 7 8 9] # 重构形状
arr1 = np.zeros((2,6)) #
print(arr1.reshape((3,4))) # 重构形状必须相乘的 相等
# [[0. 0. 0. 0.]
# [0. 0. 0. 0.]
# [0. 0. 0. 0.]] # numpy 数组运算
# +-*/
arr = np.ones((3,4)) * 4
print(arr)
# [[4. 4. 4. 4.]
# [4. 4. 4. 4.]
# [4. 4. 4. 4.]] arr = np.ones((3,4)) + 4
print(arr)
# [[5. 5. 5. 5.]
# [5. 5. 5. 5.]
# [5. 5. 5. 5.]] # numpy 数组运算函数 了解——————-
print(np.sin(arr))
# [[-0.95892427 -0.95892427 -0.95892427 -0.95892427]
# [-0.95892427 -0.95892427 -0.95892427 -0.95892427]
# [-0.95892427 -0.95892427 -0.95892427 -0.95892427]] # 矩阵运算 -- 点乘
arr1 = np.array([
[1, 2, 3],
[4, 5, 6]
]) arr2 = np.array([
[1, 2],
[4, 5],
[6, 7]
])
print(np.dot(arr1,arr2))
# [[27 33]
# [60 75]] # 求逆
arr = np.array([[1, 2, 3], [4, 5, 6], [9, 8, 9]])
print(np.linalg.inv(arr))
# [[ 0.5 -1. 0.5 ]
# [-3. 3. -1. ]
# [ 2.16666667 -1.66666667 0.5 ]] # numpy 数组数学和统计方法 arr = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(np.sum(arr[:,:]))
# 21 # 生成随机数
print(np.random.rand(3,4))
# [[0.76654824 0.23510842 0.79989748 0.93094884]
# [0.97155472 0.29956374 0.27754847 0.91103403]
# [0.43714323 0.7549109 0.14547903 0.20511579]] print(np.random.random((3,4)))
# [[0.91673193 0.15218486 0.32976182 0.41812734]
# [0.33360061 0.20190749 0.48689467 0.46679115]
# [0.12490532 0.50441629 0.95525997 0.5402791 ]] # 针对一维 随机选择数字
print(np.random.choice([1,2,3],1))
# [1] # 追对某一范围
print(np.random.randint(1,100,(3,4)))
# [[33 40 93 18]
# [80 65 64 51]
# [66 6 83 10]]

matplotlib 模块

matplotlib 模块 就是用来画图的

# 条形图

from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties # 设置字体,不然画出来会乱码
font = FontProperties(fname=r"C:\Windows\Fonts\simsun.ttc") # 设置背景
plt.style.use("ggplot") # 定义 行 列 信息
clas = ["3班","4班","5班","6班"]
students = [50,55,45,60]
clas_index = range(len(clas)) # 开始画
plt.bar(clas_index,students,color="darkblue") plt.xlabel("学生",FontProperties=font)
plt.xlabel("学生人数",FontProperties=font)
plt.title("班级-学生人数",FontProperties=font,Fontsize=25,fontweight=20)
plt.xticks(clas_index,clas,FontProperties=font) # 展示
plt.show()

# 直方图
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties # 设置字体,不然画出来会乱码
font = FontProperties(fname=r"C:\Windows\Fonts\simsun.ttc")
plt.style.use("ggplot") # 生成随机数对象
x1 = np.random.randn(10000)
x2 = np.random.randn(10000) # 生成画布
fig = plt.figure() # 每行每列
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2) ax1.hist(x1,bins=50,color="darkblue")
ax2.hist(x2,bins=50,color="y") fig.suptitle("两个正太分布",FontProperties=font,fontsize=20)
ax1.set_title("x1的正态分布",FontProperties=font)
ax2.set_title("x2的正态分布",FontProperties=font) # 展示
plt.show()

# 折线图

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties # 设置字体,不然画出来会乱码
font = FontProperties(fname=r"C:\Windows\Fonts\simsun.ttc")
plt.style.use("ggplot") np.random.seed(10) x1 = np.random.randn(40).cumsum()
x2 = np.random.randn(40).cumsum()
x3 = np.random.randn(40).cumsum()
x4 = np.random.randn(40).cumsum() plt.plot(x1,color="r",linestyle="-",marker="o",label="红圆线")
plt.plot(x2,color="y",linestyle="--",marker="*",label="黄虚线")
plt.plot(x3,color="b",linestyle="-.",marker="s",label="蓝方线")
plt.plot(x4,color="black",linestyle=":",marker="s",label="黑方线")
plt.legend(loc="best",prop=font) # 展示
plt.show()

# 散点图 + 直线图
import numpy as np
from matplotlib import pyplot as plt # 约定俗成
from matplotlib.font_manager import FontProperties # 修改字体 # 设置字体,不然画出来会乱码
font = FontProperties(fname='C:\Windows\Fonts\simsun.ttc')
plt.style.use('ggplot') fig = plt.figure()
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2) x = np.arange(20)
y = x ** 2
x2 = np.arange(20)
y2 = x2 ** 2 ax1.scatter(x,y,color="r",label="红")
ax2.scatter(x2,y2,color="b",label="蓝") ax1.plot(x,y)
ax2.plot(x2,y2) fig.suptitle("两张图",FontProperties=font,fontsize=15)
ax1.set_title("散点图",FontProperties=font)
ax2.set_title("折线图",FontProperties=font)
ax1.legend(prop=font) # 展示
plt.show()

pandas 模块

pandas 模块 操作excel/json/sql/ini/csv文件的

import pandas as pd
import numpy as np np.random.seed(10) # 生成6个月份
index = pd.date_range("2019-01-01",periods=6,freq="M")
print(index)
columns = ["c1","c2","c3","c4"] # 生成随机数
val = np.random.randn(6,4) df = pd.DataFrame(index=index,columns=columns,data=val)
print(df)
# c1 c2 c3 c4
# 2019-01-31 1.331587 0.715279 -1.545400 -0.008384
# 2019-02-28 0.621336 -0.720086 0.265512 0.108549
# 2019-03-31 0.004291 -0.174600 0.433026 1.203037
# 2019-04-30 -0.965066 1.028274 0.228630 0.445138
# 2019-05-31 -1.136602 0.135137 1.484537 -1.079805
# 2019-06-30 -1.977728 -1.743372 0.266070 2.384967 # 保存成 xlsx 文件
df.to_excel("date_c.xlsx")
# 读出文件
df = pd.read_excel("date_c.xlsx",index_col=[0])
print(df)
# c1 c2 c3 c4
# 2019-01-31 1.331587 0.715279 -1.545400 -0.008384
# 2019-02-28 0.621336 -0.720086 0.265512 0.108549
# 2019-03-31 0.004291 -0.174600 0.433026 1.203037
# 2019-04-30 -0.965066 1.028274 0.228630 0.445138
# 2019-05-31 -1.136602 0.135137 1.484537 -1.079805
# 2019-06-30 -1.977728 -1.743372 0.266070 2.384967 ###############
print(df.index)
print(df.columns)
print(df.values) print(df[['c1', 'c2']]) # 按照index取值
# print(df['2019-01-31'])
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)

Python-数据分析模块的更多相关文章

  1. python初略复习(2)及python相关数据分析模块的介绍

    常用模块 Python中的模块在使用的时候统一都是采用的句点符(.) # 就是模块名点方法的形式 import time time.time() import datetime datetime.da ...

  2. 【Python数据分析】Python3多线程并发网络爬虫-以豆瓣图书Top250为例

    基于上两篇文章的工作 [Python数据分析]Python3操作Excel-以豆瓣图书Top250为例 [Python数据分析]Python3操作Excel(二) 一些问题的解决与优化 已经正确地实现 ...

  3. 【Python数据分析】Python3操作Excel(二) 一些问题的解决与优化

    继上一篇[Python数据分析]Python3操作Excel-以豆瓣图书Top250为例 对豆瓣图书Top250进行爬取以后,鉴于还有一些问题没有解决,所以进行了进一步的交流讨论,这期间得到了一只尼玛 ...

  4. Python数据分析之numpy学习

    Python模块中的numpy,这是一个处理数组的强大模块,而该模块也是其他数据分析模块(如pandas和scipy)的核心. 接下面将从这5个方面来介绍numpy模块的内容: 1)数组的创建 2)有 ...

  5. 关于Python pandas模块输出每行中间省略号问题

    关于Python数据分析中pandas模块在输出的时候,每行的中间会有省略号出现,和行与行中间的省略号....问题,其他的站点(百度)中的大部分都是瞎写,根本就是复制黏贴以前的版本,你要想知道其他问题 ...

  6. Python数据分析基础教程

    Python数据分析基础教程(第2版)(高清版)PDF 百度网盘 链接:https://pan.baidu.com/s/1_FsReTBCaL_PzKhM0o6l0g 提取码:nkhw 复制这段内容后 ...

  7. Python数据分析基础PDF

    Python数据分析基础(高清版)PDF 百度网盘 链接:https://pan.baidu.com/s/1ImzS7Sy8TLlTshxcB8RhdA 提取码:6xeu 复制这段内容后打开百度网盘手 ...

  8. Python数据分析入门

    Python数据分析入门 最近,Analysis with Programming加入了Planet Python.作为该网站的首批特约博客,我这里来分享一下如何通过Python来开始数据分析.具体内 ...

  9. (python数据分析)第03章 Python的数据结构、函数和文件

    本章讨论Python的内置功能,这些功能本书会用到很多.虽然扩展库,比如pandas和Numpy,使处理大数据集很方便,但它们是和Python的内置数据处理工具一同使用的. 我们会从Python最基础 ...

  10. Python数据分析--Pandas知识点(二)

    本文主要是总结学习pandas过程中用到的函数和方法, 在此记录, 防止遗忘. Python数据分析--Pandas知识点(一) 下面将是在知识点一的基础上继续总结. 13. 简单计算 新建一个数据表 ...

随机推荐

  1. GPIO, AFIO

    o read/write the AFIO_EVCR, AFIO_MAPR and AFIO_EXTICRX registers, the AFIO clock should first be ena ...

  2. Memory barrier,

    A memory barrier, also known as a membar, memory fence or fence instruction, 是一种屏障指令,它使中央处理单元(CPU)或编 ...

  3. 网页添加Live2D看板娘

    看板娘简而言之就是小店的女服务生,也有“吸引顾客,招揽生意,提高人气”等作用类似品牌形象代言人的含义. 如果想放一个呆萌的看板娘在博客上 js <script type="text/j ...

  4. 2018北京网络赛 G The Mole /// 分块暴力 点线距离

    题目大意: 给定n段线段 编号为1~n 接下来m个询问 给定一点 输出离该点最近的线段的最小编号(距离相等时取编号小的) 题解 大致就是 1.坐标范围为(0,2^16-1) 将坐标系划分为2^8*2^ ...

  5. USACO2007 Protecting the Flowers /// 比值 前缀和 oj21161

    题目大意: 有N (2 ≤ N ≤ 100,000) 头牛偷吃花 将牛赶回牛棚需Ti minutes (1 ≤ Ti ≤ 2,000,000) 每头牛每分钟能吃Di (1 ≤ Di ≤ 100) 朵花 ...

  6. PAT L2-019. 悄悄关注 /// map set

    https://www.patest.cn/contests/gplt/L2-019 题目大意: 新浪微博上有个“悄悄关注”,一个用户悄悄关注的人,不出现在这个用户的关注列表上,但系统会推送其悄悄关注 ...

  7. exe4j 打包(多个jar打包)

    一,自行下载exe4j 注册码: 用户名和公司名可随便填A-XVK258563F-1p4lv7mg7savA-XVK209982F-1y0i3h4ywx2h1A-XVK267351F-dpurrhny ...

  8. Sqlite && EF Code FIRST 终极解决方案 2019.5.17

    Sqlite && EF Code FIRST 终极解决方案 2019.5.17 包括根据模型自动生成数据库,初始化数据,模型改变时的自动数据迁移等 2019.12.25 更新 支持E ...

  9. [JZOJ3348] 【NOI2013模拟】秘密任务

    题目 题目大意 给你一个无向图,你要割掉一些边使得\(1\)到\(n\)的所有最短路径被阻截. 割掉一个边\((u,v)\)的代价为\(a_u\)或\(a_v\)(记为两种不同的方案). 问最小代价及 ...

  10. thinkphp url生成

    为了配合所使用的URL模式,我们需要能够动态的根据当前的URL设置生成对应的URL地址,为此,ThinkPHP内置提供了U方法,用于URL的动态生成,可以确保项目在移植过程中不受环境的影响. 定义规则 ...