import numpy as np

NumPy : numberial python

NumPy的核心:数据结构 ndarray

1.1 数组方法

np.array 创建数组 基本语法:np.array([[],[],[]……[]])

# 生成1 维数组
a = np.array([1,2,3,4])
a
array([1, 2, 3, 4])
#生成二维数组
a = np.array([
[1,2,3,4],
[5,6,7,8],
[7,7,7,7]
])
a
array([[1, 2, 3, 4],
[5, 6, 7, 8],
[7, 7, 7, 7]])

我们还可以使用np.arange(start,stop,step,dtype)生成等差数组

·start 表示开始数字 为下确界 默认为0

·stop 表示结束的数 为上界

·step 表示公差 默认为1

·dtype 指定数据类型 默认inter32

因为start、step和dtype都有默认值,所以可以只写入stop

#下面创建一个从0到9的数组
np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
#创建首项为1 截止到10(不包含) 指定步长2
np.arange(1,10,2)
array([1, 3, 5, 7, 9])

np.linspace(start,stop,num,endpoint)使得我们可以不必计算公差来生成一个等差数组

·num 该等差数组的个数

·endpoint 序列中是否包含stop值,注意这里默认为true

explain:这个方法主要是我们知道首尾之后使用的,所以endpoint默认为true

#比如我们只知道一个数组首项为0,最后一项为10,且该数组有5个数
np.linspace(0,10,5)
array([ 0. ,  2.5,  5. ,  7.5, 10. ])

np.reshape 改变数组的形状

#将一个一维数组转为二维
np.arange(10).reshape(2,5)
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])

有一些比较特殊的数组我们可以numpy提供了一键生成的方法

#都是1的数组可以使用np.ones来生成 参数为矩阵的形状
#可以用np.ones_like(a)来生成和a形状一样的数组
#默认为1维
np.ones(10) # 生成一维十个分量都为一的数组
np.ones((2,5)) #生成二维每个维度的五个等量都为一的数组
array([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]])

同理,可以生成所需的全为零(zeros),没有初始化(empty),特定数(full)的数组

使用random随机函数创建数组

#创建五个范围在[0,1)之间的数据
#这里需要说明:random函数生成的范围为左闭右开
np.random.rand(5)
array([0.44632437, 0.81121282, 0.80482189, 0.41552902, 0.92565849])
#指定shape
np.random.rand(3,4)
array([[0.38044668, 0.18780878, 0.88673987, 0.5911139 ],
[0.93546119, 0.64607342, 0.62441079, 0.74648861],
[0.5757769 , 0.16007626, 0.55954991, 0.55501118]])
#randint(low,high,(shape))生成随机整数 区间[low,high)
#low默认为0
np.random.randint(1,10,(3,4))
array([[9, 7, 8, 9],
[5, 9, 5, 1],
[3, 7, 9, 6]])
#uniform()生成在[low,high)之间均匀分布的数字
np.random.uniform(1,10,(3,4))
array([[6.03188774, 3.39992438, 3.56467481, 2.58653308],
[2.85072574, 2.46446551, 6.80989601, 1.84529343],
[2.98288733, 7.39698989, 7.89446111, 7.4762518 ]])
#randn()生成的数据具有标准正态分布 均值为0,方差为1
np.random.randn(3,4)
array([[ 0.82166166,  0.44499244, -1.82220382, -0.04496252],
[ 0.31283332, -1.4152152 , 1.12381001, 1.88690788],
[-0.121892 , -0.48383337, -0.19617823, -2.80674969]])
#normal() 可以指定均值和标准差
np.random.normal(5,10,(3,4))
array([[14.78332891, 23.10401466, -2.25248365,  6.21926006],
[ 8.4929957 , 3.29216256, -3.71472177, 1.58433458],
[-4.55193955, 3.40607897, -9.00472229, 6.96018844]])
#choice(给定数组,结果的shape) 从给定的数组中,产生随机结果
np.random.choice(5,(2,3))
#等同于 np.random.choice(0,5,3)
array([[3, 4, 1],
[0, 4, 2]])
#shuffle 把一个数组的分量随机排列
(array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]]),
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]]))

1.2 数组属性:

#生成二维数组
a = np.array([
[1,2,3,4],
[5,6,7,8],
[7,7,7,7]
])
a
array([[1, 2, 3, 4],
[5, 6, 7, 8],
[7, 7, 7, 7]])
# ndim 返回一个数组的维度
a.ndim
2
#shape 返回一个元组 array的维度和每个维度有几个分量
#系数矩阵的形状
a.shape
(3, 4)
#dtype array中元素的数据类型
a.dtype
dtype('int32')
#size 返回一个array中所有元素的加总值
a.size
12
#itemsize 返回数组中每个元素的大小
a.itemsize
4

1.3 数组索引 大致和原生List相同

基础索引

#首先创建一个数组
x = np.arange(10)
#取出x中的第一个元素的值
#注意:缩影是从0开始的
x[0]
0
# 取值2-8
# 数组的数也是从0开始的,所以2的索引为2
# 又因为8靠近数组的上界,所以索引可以用-2
# 但是当我们使用区间来表示索引的时候 区间的范围是左闭右开
x[2:-1]
array([2, 3, 4, 5, 6, 7, 8])
#再生成一个多维数组
y = np.arange(20).reshape(4,5)
y
array([[ 0,  1,  2,  3,  4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
y.ndim
2
#取第二行第一列的数据
#行列的索引也是从0开始
y[0,0]
0
#取所有第二行的元素
y[1]
array([5, 6, 7, 8, 9])
#取所有第二列的元素
y[:,1]
array([ 1,  6, 11, 16])
x[:2] = 666 #修改数表中的元素是索引最大的作用
x
array([666, 666,   2,   3,   4,   5,   6,   7,   8,   9])
y[1,0] = 1
y
array([[ 0,  1,  2,  3,  4],
[ 1, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])

切片 basic slicing

需要注意的是:基础切片产生的是view,而修改view会对原来的数组产生影响

可以使用以下方法来切片

slice object (constructed by start:stop:step notation inside of brackets)(等差数列) i:j:k

an integer

a tuple of slice objects and integers.

Ellipsis and newaxis objects can be interspersed with these as well.(维度索引)

维度索引工具

There are some tools to facilitate the easy matching of array shapes with expressions and in assignments.

Ellipsis

expands to the number of : objects needed for the selection tuple to index all dimensions.

所以 ... 把 : 拓展到了所有维度的index上,

x = np.array([
[[1],[2],[3]],
[[4],[5],[6]]
])
x[...,0]
array([[1, 2, 3],
[4, 5, 6]])
x[:,:,0]
array([[1, 2, 3],
[4, 5, 6]])

newaxis

expand the dimensions of the resulting selection by one unit-length dimension.The added dimension is the position of the newaxis object in the selection tuple.

newaxis = None

new一个axis,添加一个维度.

x[:, np.newaxis, :, :].shape # 原来是2,3,1 现在添加了一个维度
(2, 1, 3, 1)
x[:, None, :, :].shape # 功能相同
(2, 1, 3, 1)

This can be handy to combine two arrays in a way that otherwise would require explicit reshaping operations. For example:

x = np.arange(5)
a = x[:,np.newaxis]
b = x[np.newaxis,:]
# x[:,np.newaxis] + x[np.newaxis,:]
a , b
(array([[0],
[1],
[2],
[3],
[4]]),
array([[0, 1, 2, 3, 4]]))
a + b
array([[0, 1, 2, 3, 4],
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8]])

索引进阶:整数索引,布尔索引

整数索引

学习之前,我们先来看看官方文档上的一个tip

Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view).

返回的是一个副本,在副本上操作不会改变原来的array

copy和view辨析

The definition of advanced indexing means that x[(1, 2, 3),] is fundamentally different than x[(1, 2, 3)]. The latter is equivalent to x[1, 2, 3] which will trigger basic selection while the former will trigger advanced indexing. Be sure to understand why this occurs.

Also recognize that x[[1, 2, 3]] will trigger advanced indexing, whereas due to the deprecated Numeric compatibility mentioned above, x[[1, 2, slice(None)]] will trigger basic slicing.

Thus, x[ind1, ..., ind2,:] acts like x[ind1][..., ind2, :] under basic slicing.This not true for advanced indexing.

x = np.arange(64).reshape(4,4,4) # 三维数组
a = x[(1,2,3),]#在最高维度上的index是1,2,3
b = x[(1,2,3)]#在第三维度上的index是1,第二维度上的index是2,第一维度上的index是3
c = x[[1,2,3]]
d = x[1][2][3],
#d = x[[1,2,slice(None)]]#弃用了的数字兼容性
x,a,b,c,d
(array([[[ 0,  1,  2,  3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]], [[16, 17, 18, 19],
[20, 21, 22, 23],
[24, 25, 26, 27],
[28, 29, 30, 31]], [[32, 33, 34, 35],
[36, 37, 38, 39],
[40, 41, 42, 43],
[44, 45, 46, 47]], [[48, 49, 50, 51],
[52, 53, 54, 55],
[56, 57, 58, 59],
[60, 61, 62, 63]]]),
array([[[16, 17, 18, 19],
[20, 21, 22, 23],
[24, 25, 26, 27],
[28, 29, 30, 31]], [[32, 33, 34, 35],
[36, 37, 38, 39],
[40, 41, 42, 43],
[44, 45, 46, 47]], [[48, 49, 50, 51],
[52, 53, 54, 55],
[56, 57, 58, 59],
[60, 61, 62, 63]]]),
27,
array([[[16, 17, 18, 19],
[20, 21, 22, 23],
[24, 25, 26, 27],
[28, 29, 30, 31]], [[32, 33, 34, 35],
[36, 37, 38, 39],
[40, 41, 42, 43],
[44, 45, 46, 47]], [[48, 49, 50, 51],
[52, 53, 54, 55],
[56, 57, 58, 59],
[60, 61, 62, 63]]]),
27)
x = np.arange(10)
indexs = np.array([
[0,2],
[1,3]
])
x[indexs]
x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

二维数组中的使用方法

y[[r_1,r_2,……,r_n],[c_1,c_2,……,c_n]]

r_i为第i个元素的行,c_i为第i个元素的列

y = np.arange(20).reshape(4,5)
y
array([[ 0,  1,  2,  3,  4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
y[[0,2],[0,1]]
array([ 0, 11])

布尔索引

x = np.arange(10)
x > 6
x[ x > 6]#返回x>6为真时索引对应的元素
array([7, 8, 9])

谈到布尔我们就不得不谈一下布尔运算符号 & |

x = np.arange(10)
condition = (x%2 == 0) | (x > 7)
x[condition]
array([0, 2, 4, 6, 8, 9])

1.4数组运算

#基础运算和矩阵是一致的
#但是两个数组的乘法是单纯的对应相乘
# 2*3的矩阵和3*2的矩阵运算
a = np.arange(6,12).reshape(2,3)
b = np.random.randint(2,10,(2,3))
a,b
(array([[ 6,  7,  8],
[ 9, 10, 11]]),
array([[2, 8, 6],
[8, 7, 9]]))
a * b
array([[12, 56, 48],
[72, 70, 99]])

1.4.1预置函数

#sum求和函数
#prod乘积
#cumsum累加
#cumprod累乘
#min最小值
#max最大值
#quantile 获取四分位的数值
#median中位数
#mean平均数
#std标准差
#var方差
#average(数据,权值)加权平均

1.5 axis参数

axis = 0 表示行,axis = 1 表示列

对于sum/mean/media等聚合函数

  • axis = 0 表示把行消解掉 跨行运算
  • axis = 1 表示把列消解掉,跨列运算

1.6 添加维度

1.6.1 上文讲到的newaxis

1.6.2 np.expand_dims

np.expand_dims(arr,axis = 0|1)

1.6.3 np.reshape

1.7 数组合并

1.7.1合并行

a = np.arange(6).reshape(2,3)
b = np.arange(6,18).reshape(4,3)

我们发现a,b列数相同

np.concatenate([a,b])
np.vstack([a,b])
np.row_stack([a,b])

1.7.2合并列

a = np.arange(12).reshape(3,4)
b = np.arange(12,18).reshape(3,2)

我们发现a,b行数相同

np.concatenate([a,b],axis=1)
np.hstack([a,b])
np.column_stack([a,b])

前菜--Numpy的更多相关文章

  1. 另一份Java应用调优指南之-前菜

    每一次成功的调优,都会诞生又一份的调优指南. 一些必须写在前面的军规,虽然与Java应用的调优没直接关联,但是测试同学经常不留神的地方. 1 独占你的测试机器 包括跑JMeter的那些机器. &quo ...

  2. Java-Netty前菜-NIO

    NIO NIO主要有三个核心部分组成: buffer缓冲区 Channel管道 Selector选择器 在NIO中并不是以流的方式来处理数据的,而是以buffer缓冲区和Channel管道配合使用来处 ...

  3. Numpy中数据的常用的保存与读取方法

    小书匠 深度学习  文章目录: 1.保存为二进制文件(.npy/.npz) numpy.save numpy.savez numpy.savez_compressed 2.保存到文本文件 numpy. ...

  4. Python Numpy中数据的常用的保存与读取方法

    在经常性读取大量的数值文件时(比如深度学习训练数据),可以考虑现将数据存储为Numpy格式,然后直接使用Numpy去读取,速度相比为转化前快很多. 下面就常用的保存数据到二进制文件和保存数据到文本文件 ...

  5. numpy学习笔记02

    简介 numpy.array() 数组对象,可以表示普通的一维数组,或者二维矩阵,或者任意数据:并且它可以对数组中的数据进行非常高效的运算,如:数据统计.图像处理.线性代数等 numpy 之所以能运行 ...

  6. 2016中国·西安“华山杯”WriteUp- SeeSea

    题目打包下载:https://yunpan.cn/ckyrKxHJDPAIN (提取码:bbaf) Web 1.签到(10) 扫码回复 hs_ctf拿flag, 套路题. flag_Xd{hSh_ct ...

  7. PHPCMS 插件开发教程及经验谈

    虽说 PHPCMS 开源,但其它开发文档及参考资料实在少得可怜.进行二次开发时,自己还得慢慢去研究它的代码,实在让人郁闷. PHPCMS 的“Baibu/Google地图”实在有待改进,对于数据量比较 ...

  8. 学了Java 你未必知道这些

    作为一个正奔跑向编程完美天堂的朝圣者,本人觉得在平常的编程中,应该要做到以下几点: 一:汝应注释,这样做既方便别人,也方便自己去读懂代码的逻辑 二:注重细节,为自己写的每行代码负责,比如,在并发编程的 ...

  9. MC34063+MOSFET扩流 12V-5V 折腾出了高效率电路(转)

    源:http://www.amobbs.com/thread-5484710-1-1.html 从网上找到一些MC34063扩流降压电路图,一个个的试,根本达不到我的基本要求,全都延续了34063的降 ...

  10. ToolStrip和MenuStrip控件簡介及常用屬性(转)

    ToolStrip和MenuStrip實際上是相同的控件,因為MenuStrip直接派生於ToolStrip.也就是說ToolStrip可以做的工作,MenuStrip也能完成. ToolStrip( ...

随机推荐

  1. MyBatis(介绍和环境配置)

    ORM(Object Relational Mapping)  设计模式,思想 对象关系映射,是一种数据持久化技术.它在对象模型和关系型数据库之间建立起对应关系,并且提供了一种机制,通过JavaBea ...

  2. Spring的同一个服务为什么会加载多次?

    问题现象 最近在本地调试公司的一个Web项目时,无意中发现日志中出现了两次同一个服务的init记录,项目都是基于Spring来搭建的,按理说服务都是单例的,应该只有一次服务加载日志才对,本着对工作认真 ...

  3. selenium4-定位单个页面元素

    在操作各项页面元素之前,先介绍下如何通过Python代码来找到这些元素.WebDriver提供了18种元素定位方法,共分为两类(定位当个元素.定位组元素),本节先举例详细介绍下selenium4-定位 ...

  4. HTML+CSS基础知识(4)简单的广告界面

    文章目录 1.网页实例 1.1 代码 1.2 测试效果 1.网页实例 1.1 代码 css样式 /* 清除页面样式 */ *{ margin:0; padding: 0; } /* 统一页面的样式 * ...

  5. 京东云开发者|京东云RDS数据迁移常见场景攻略

    云时代已经来临,云上很多场景下都需要数据的迁移.备份和流转,各大云厂商也大都提供了自己的迁移工具.本文主要介绍京东云数据库为解决用户数据迁移的常见场景所提供的解决方案. 场景一:数据迁移上云 数据迁移 ...

  6. element-ui v-table 复选框默认选中

    <el-table ref="refTable" :data="list" v-loading="listLoading" eleme ...

  7. 「MySQL高级篇」MySQL锁机制 && 事务

    大家好,我是melo,一名大三后台练习生,最近赶在春招前整理整理发过的博客~! 引言 锁锁锁,到哪到离不开这桩琐事,并发琐事,redis琐事,如今是MySQL琐事,这其中琐事,还跟MySQL另一个重要 ...

  8. iptables规则查询

    iptables规则查询 之前在iptables的概念中已经提到过,在实际操作iptables的过程中,是以"表"作为操作入口的,如果你经常操作关系型数据库,那么当你听到" ...

  9. 利用递归的方式在JSON 数据中找到某个节点的多有父节点

    在项目中遇到的问题-- 一个级联题,知道答案id  后将每一级的选项展示出来 例如 级联题的 json 数据是 [ { name: '北京', id: 1, children:[ { name: '朝 ...

  10. 新版的Eureka已经移除了基于Ribbon的客户端的负载均衡

    启用一个EurekaServer和一个服务调用方,两个copy的服务提供方. 本次测试用Springcloud 2021.0.1版本 客户端使用RestTemplate 的负载均衡 @LoadBala ...