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. Python编程之定时任务(crontab)详解

    引言 python-crontab是python模块,提供了对cron任务的访问,并使得我们可以通过python对crontab文件进行修改. 安装 pip install python-cronta ...

  2. 【C++】spdlog光速入门,C++logger最简单最快的库

    参考文档:https://spdlog.docsforge.com/master/ spdlog简介 Very fast, header only, C++ logging library. 一个he ...

  3. resultMap处理字段和属性的映射关系

    1.resultMap处理字段和属性的映射关系 若字段名和实体类中的属性名不一致,则可以通过resultMap设置自定义映射 <!-- resultMap:设置自定义映射 属性: id:表示自定 ...

  4. 【C++】GoogleTest进阶之gMock

    gMock是什么 当我们去写测试时,有些测试对象很单纯简单,例如一个函数完全不依赖于其他的对象,那么就只需要验证其输入输出是否符合预期即可. 但是如果测试对象很复杂或者依赖于其他的对象呢?例如一个函数 ...

  5. uoj131【NOI2015】品酒大会

    题目链接 很容易想到p和q"r相似"就等价于在后缀数组中q与p之间的height值\(\ge r\),也就是说\(<r\)的那些height值会把排好序后的后缀分割成若干段, ...

  6. win10安装pip

    Windows如何安装pip?请看下面方法: 1.搜索pip 2.点击下载文件. 3.下载压缩包 6.解压到桌面. 7.进入解压目录,按住Shift点击右键,选择打开powershell 8.执行py ...

  7. 一文理解Cookie、Session

    一文理解Cookie.Session 1.什么是会话 用户打开浏览器,点击多个超链接,访问服务器的多个web资源,然后关闭浏览器,整个过程就称为一个会话: HTTP 是无状态,有会话的 HTTP 是无 ...

  8. 【lwip】10-ICMP协议&源码分析

    目录 前言 10.1 ICMP简介 10.2 ICMP报文 10.2.1 ICMP报文格式 10.2.2 ICMP报文类型 10.2.3 ICMP报文固定首部字段意义 10.3 ICMP差错报告报文 ...

  9. 畅联新设备接入情况:新增威隆NB烟感

    双美接入,应该是电信AEP平台的. ---------------------------------------------------------------------------------- ...

  10. created与mounted执行顺序(关于微任务与宏任务)

    1.ps:只要你只使用created或者mounted中的一个不就好了吗[dog].这样只要在第一个异步任务代码跳出前,嵌套第二个任务函数就好了 最后面的两个链接一个是微任务与宏任务的通俗例子,一个是 ...