shape: 数组的形状;
dtype: 数据类型;
buffer: 对象暴露缓存区接口;
offset: 数组数据的偏移量;
strides: 数据步长
order:{'C','F'},以行或列为主排列顺序
1.从Python数组结构列表,元组等转换;
2.使用np.arange,np.ones,np.zeros等numpy原生方法;
3.从存储空间读取数组;
4.通过使用字符串或缓冲区从原始字节创建数组;
5.使用特殊函数,如random
使用numpy.array将列表或元组转换为ndarray数组:
numpy.array(object,dtype=None,copy=True,order=None,subok=False,ndmin=0)
参数:
1)object: 列表、元组等
2)dtype: 数据类型。默认对象所需的最小类型
3)copy: 布尔类型,默认为True,表示复制对象
# 例:
import numpy as np
l=list('123456')
nd2 = np.array(l)
print(nd2)
# ['1' '2' '3' '4' '5' '6']
type(nd2)
# numpy.ndarray
arange()的功能是在给定区间内创建一系列均匀间隔的值:
numpy.arange(start,stop,step,dtype=None)
设置值所在区间,这里为 '[start,stop)',这是一个半开半闭区间,step为步长用于设置值之间的间隔,dtype为设置值类型
# 例:
import numpy as np
nd3 = np.arange(0,150,step=5,dtype=np.float32)
display(nd3.shape,nd3.dtype)
# (30,)
# dtype('float32')
nd3
# array([ 0., 5., 10., 15., 20., 25., 30., 35., 40., 45., 50.,
55., 60., 65., 70., 75., 80., 85., 90., 95., 100., 105.,
110., 115., 120., 125., 130., 135., 140., 145.], dtype=float32)
# 将数组的值到过来
np.arange(10,0,step=-1)
# array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
linspace 用于在指定区间内返回间隔均匀的值:
numpy.linspace(start,stop,num=50,endpoint=True,retstep=False,dtype=None)
1)start: 序列的起始值
2)stop: 序列的结束值
3)num: 生成的样本数,默认为50
4)endpoint: 布尔值,默认为真,表示最后一个样本包含在序列内
5)retstep: 布尔值,如果为真,返回间距,默认为False
6)dtype: 数组的类型
# 例:
import numpy as np
nd4 = np.linspace(0,15,num=16)
nd4
# array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.,
13., 14., 15.])
nd4.shape
# (16,)
# 不使用dtype属性该表默认的数据类型,就用形如以下的方式:
numpyd.astype(np.float32)
nd4.astype(np.int)
# array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
ones用于快速创建数值全部为1的多维数组:
numpy.ones(shape,dtype=None,order='C')
1)shape: 用于指定数组形状
2)dtype: 数据类型
3)order:{'C','F'},按行或列的方式存储数组
# 例:
nd5 = np.ones(shape=(2,2,3)
# array([[[1., 1., 1.],
[1., 1., 1.]],
[[1., 1., 1.],
[1., 1., 1.]]])
nd5.type
# dtype('float64')
zeros和ones方法非常类似,不同在于,这里全部填充的0:
numpy.zeros(shape,dtype=None,order='C')
1)shape: 用于指定数组形状
2)dtype: 数据类型
3)order:{'C','F'},按行或列的方式存储数组
# 例:
nd6 = np.zeros(shape=(2,2,3)
# array([[[0., 0., 0.],
[0., 0., 0.]],
[[0., 0., 0.],
[0., 0., 0.]]])
nd6.type
# dtype('float64')
full用于创建一个自定义形状的数组,可以自己指定一个值,该值填满整个矩阵
numpy.full(shape,fill_value=num)
# 例:
nd7 = np.full(shape=(2,2,3),fill_value = 125.0)
# array([[[125., 125., 125.],
[125., 125., 125.]],
[[125., 125., 125.],
[125., 125., 125.]]])
nd7.dtype
# dtype('float64')
eye用于创建一个二维数组,其特点是K对角线上的值为1,其余值全部为0,方法如下:
numpy.eye(N,M=None,k=0,dtype=)
1)N: 输出数组的行数
2)M: 输出数组的列数
3)K: 对角线索引:0(默认)是指主对角线,正值是指上对角线,负值是指下对角线
# 例:
nd8 = np.eye(5,5)
nd8
# array([[1., 0., 0., 0., 0.],
[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.]])
1. 生成随机的整数型矩阵
np.random.randint(low=0,high=150,size=(5,4))
1)low: 表示最小值
2)high: 表示最大值
3)size: 是一个元组类型
# 例:
nd1 = np.random.randint(0,150,size=(5,4))
nd1
# array([[138, 17, 78, 96],
[ 74, 87, 119, 13],
[ 30, 95, 102, 129],
[143, 145, 71, 26],
[111, 102, 90, 9]])
display(nd1.dtype)
# dtype('int32')
2.标准的正太分布
np.random.rand(10,5)
没有固定的参数,没多加一个数字,代表多增加一个维度
# 例:
nd2 = np.random.rand(5,4)
nd2
# array([[0.89228631, 0.09395712, 0.11006858, 0.50642846],
[0.19321508, 0.89265513, 0.92207087, 0.60248469],
[0.40542775, 0.0946624 , 0.4061389 , 0.05318687],
[0.47189838, 0.83371183, 0.58057428, 0.33652627],
[0.53525755, 0.01120071, 0.93071464, 0.17386506]])
3.随机抽样
np.random.random(size=None)
- size 表示形状
- random 随机生成的范围在0-1之间
nd3 = np.random.random(size=(2,2,3))
nd3
# array([[[5.55417411e-02, 2.30091478e-01, 1.90000424e-04],
[8.23200000e-01, 8.80436737e-02, 5.82663911e-02]],
[[8.55482267e-01, 5.91331148e-01, 5.42372129e-01],
[6.41506494e-03, 2.87094975e-01, 9.71351497e-01]]])
nd3.dtype
# dtype('float64')
4.标准方差,代表数据的稳定性
np.random.normal(loc=170,scale=100,size=50)
normal也是一个正太分布的方法
生成一个一维数组
- location 是定位的值
- scale 是波动值
- size 是数据长度
#例:
nd4 = np.random.normal(loc=200,scale=100,size=10)
nd4
# array([ 57.8404145 , 222.35053913, 272.15309705, 194.86087993,
141.71614044, 132.63831482, 207.34052565, 311.06350563,
170.48570481, 191.6400491 ])
5.随机数
每一个数据都是一个维度
rand 和 random 的区别:random 需要size来描述形状,而rand只需要直接给值,通过值的数量来确定形状
np.random.rand(d1,d2,dn)
# 例:
nd5 = np.random.rand(2,2,3)
nd5
# array([[[0.32031291, 0.11192557, 0.04106862],
[0.65871856, 0.34324204, 0.83270951]],
[[0.44817023, 0.99248653, 0.16035689],
[0.76711745, 0.5325966 , 0.12934012]]])
linspace 是线性生成的,是全闭区间
logspace 是线性生成的,并且以什么为底(对数)
# 例:
np.log10(100)
# 2.0
nd7 = np.logspace(0,15,num=16,base=np.e)
nd7
# array([1.00000000e+00, 2.71828183e+00, 7.38905610e+00, 2.00855369e+01,
5.45981500e+01, 1.48413159e+02, 4.03428793e+02, 1.09663316e+03,
2.98095799e+03, 8.10308393e+03, 2.20264658e+04, 5.98741417e+04,
1.62754791e+05, 4.42413392e+05, 1.20260428e+06, 3.26901737e+06])
np.diag构建对角矩阵np.diag(v,k=0)参数为列表即可
- v可以是一维或二维的矩阵
- k<0表示斜线在矩阵的下方
- k>0表示斜线在矩阵的上方
# 例:
# 满秩矩阵
np.diag([1,2,3])
# array([[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
1.csv
csv,dat是一种常用的数据格式化文件类型,为了可以从中读取数据,我们使用:
numpy.genfromtxt()
# 例:
# 使用'numpy.savetxt'我们可以将Numpy数组保存到csv文件中
M = np.random.rand(3,3)
# 不管给什么样的后缀名,都会以TXT的格式进行存储
np.savetxt('random-matrix.dat',M)
import numpy as np
data1 = np.genfromtxt('random-matrix.dat')
print(data1.shape) # (3,3)
data2 = np.loadtxt('random-matrix.dat')
print(data2) # (3,3)
data3 = np.mafromtxt('random-matrix.dat')
print(data3) # (3,3)
data4 = np.ndfromtxt('random-matrix.dat')
print(data4) # (3,3)
data5 = np.recfromtxt('random-matrix.dat')
print(data5) # (3,3)
2.Numpy 原生文件类型
使用numpy.save和numpy.load保存和读取
a = np.save('random-matrix.dat',M)
np.load('random-matrix.dat')
# array([[0.72147967, 0.96083609, 0.08819009],
[0.84168826, 0.92901361, 0.42336533],
[0.31404165, 0.09710978, 0.66129327]])
ndim,shape,size
- ndim 数组的维度(自己会计算)
- shape 形状 (如:5,4,3)
- size 数组的总长度
- dtype 查看数据类型
# 例:
nd1 = np.array([[[1, 2, 3],[1, 2, 3],[1, 2, 3]],[[1, 2, 3],[1, 2, 3],[1, 2, 3]],[[1, 2, 3],[1, 2, 3],[1, 2, 3]]])
nd1.shape
# (3,3,3)
nd1.dtype
# dtype('int32')
nd1.ndim
# 3
nd1.size
# 27
ndarray.T用于数组的转置,与.transpose()相同
# 例:
nd1 = np.array([[[1, 2, 3],[1, 2, 3],[1, 2, 3]],[[1, 2, 3],[1, 2, 3],[1, 2, 3]],[[1, 2, 3],[1, 2, 3],[1, 2, 3]]])
nd1
# array([[[1, 2, 3],
[1, 2, 3],
[1, 2, 3]],
[[1, 2, 3],
[1, 2, 3],
[1, 2, 3]],
[[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]])
nd1.T
# array([[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],
[[2, 2, 2],
[2, 2, 2],
[2, 2, 2]],
[[3, 3, 3],
[3, 3, 3],
[3, 3, 3]]])
2.实部与虚部
imag - imaginary number 虚数
ndarray.imag 用来输出数组包含元素的虚部
real - real number
ndarray.real 用来输出数组包含元素的实部
3. 字节数与总字节数
ndarray.itemsize 输出一个数组元素的字节数
ndarray.nbytes 用来输出数组的元素总字节数
ndarray strides 用来遍历数组时,输出每个维度中步进的字节元组
# 例:
nd1 = np.array([[[1, 2, 3],[1, 2, 3],[1, 2, 3]],[[1, 2, 3],[1, 2, 3],[1, 2, 3]],[[1, 2, 3],[1, 2, 3],[1, 2, 3]]])
nd1.dtype
# dtype('int32')
# int32 -> int 4个字节
nd1.itemsize
# 4
nd1.size
# 27
# 27个基本元素,每个元素都是int32类型,那么每个元素占用4个字节,27*4
nd1.nbytes
# 108
nd1.shape
(3,3,3)
# 第一个是最外层数组,占用4个字节,有3个第二维,3*4 ,第三个维度也有3个元素,所以3*(3*4)
nd1.strides[::-1]
# (4,12,36)
一维与列表完全一致
# 例:
# png图片的RGB取值范围是0-1
# 彩色图片是三维的,黑白图片是二维的
import matplotlib.pyplot as plt
# 读取图片
fish = plt.imread('fish.png')
# 展示图片
plt.imshow(fish)
# 颠倒图片
fish.shape
# (326,243,3)
# 左右颠倒
fish1 = fish[:,::-1]
plt.imshow(fish1)
# 上下颠倒
fish2 = fish1[::-1]
plt.imshow(fish2)
# RGB进行颠倒
fish3 = fish2[:,:,::-1]
plt.imshow(fish3)
# 例:把鱼头换成狗头
fish = plt.imread('fish.png')
dog = plt.imread('dog.jpg')
fish.shape # (326,243,3)
dog.shape = (300,313,3)
# 取狗头与鱼头
dog[50:150,70:190]
fish[50:150,70:190]
# 查看狗,鱼类型
display(fish.dtype,dog.dtype)
# dtype('float32')
# dtype('unit8')
# fish图片是png, dog图片是jpg
# 转换并替换
dogface_fish = fish[50:150,70:190]=dog[50:150,70:190].astype(np.float32)/255
plt.imshow(fish)
2.重设形状
reshape 可以在不改变数组数据的同时,改变数组的形状,其中,numpy.reshape()等效于ndarray.reshape()
# 例:
nd1 = np.random.randint(0,150,size=(5,4))
nd1
# array([[ 47, 139, 112, 19],
[ 9, 82, 5, 132],
[ 63, 71, 123, 23],
[ 40, 40, 26, 147],
[143, 89, 93, 94]])
# reshape(value) val可以是单个值,这个值可以是list,也可以是tuple
# 如果是多个值,则这多个值的乘积等于原先shape的乘积
nd1.reshape(10,2)
# array([[ 47, 139],
[112, 19],
[ 9, 82],
[ 5, 132],
[ 63, 71],
[123, 23],
[ 40, 40],
[ 26, 147],
[143, 89],
[ 93, 94]])
3.数组展开
ravel 的目的是将任意形状的数组扁平化,变为1维数组
# 例:
nd1.ravel()
# array([ 47, 139, 112, 19, 9, 82, 5, 132, 63, 71, 123, 23, 40,
40, 26, 147, 143, 89, 93, 94])
4.级联
np.concatenate()级联需要注意的点:
- 级联的参数是列表: 一定要加中括号或小括号
- 维度必须相同
- 形状相符
- 【重点】级联的方向默认是shape这个tuple的第一个值所代表的维度方向
- 可通过axis参数改变级联的方向,默认为0,(0表示列相连,表示的是X轴的事情,1表示行相连,Y轴的事情)
# 例:
nd2 = np.random.randit(0,150,size=(5,4))
nd3 = np.random.randit(0,150,size=(5,4))
display(nd2,nd3)
# array([[ 33, 138, 54, 1],
[ 42, 72, 108, 4],
[132, 23, 75, 18],
[109, 24, 139, 82],
[ 38, 104, 26, 61]])
array([[ 87, 96, 128, 60],
[ 60, 134, 121, 113],
[ 60, 114, 56, 10],
[ 14, 72, 124, 89],
[ 2, 121, 26, 42]])
# axis默认值是0,表示的是对Y轴进行合并,或者说是垂直合并
# 垂直合并影响的是列,那么也就是说,列的个数必须相等
np.concatenate((nd2,nd3),axis=0)
# array([[ 33, 138, 54, 1],
[ 42, 72, 108, 4],
[132, 23, 75, 18],
[109, 24, 139, 82],
[ 38, 104, 26, 61],
[ 87, 96, 128, 60],
[ 60, 134, 121, 113],
[ 60, 114, 56, 10],
[ 14, 72, 124, 89],
[ 2, 121, 26, 42]])
# axis值是1 ,表示的是对x轴进行合并,或者说是水平合并
# 水平合并影响的是行,那么也就是说,行的个数必须相等
np.concatenate((nd2,nd3),axis=1)
array([[ 33, 138, 54, 1, 87, 96, 128, 60],
[ 42, 72, 108, 4, 60, 134, 121, 113],
[132, 23, 75, 18, 60, 114, 56, 10],
[109, 24, 139, 82, 14, 72, 124, 89],
[ 38, 104, 26, 61, 2, 121, 26, 42]])
4.1 numpy.[hstack|vstack]
分别代表水平级联与垂直级联,填入的参数必须被小括号或中括号包裹
vertical垂直的horizontal水平的stack乘积
这两个函数的值也是一个list或tuple
5.分割数组
numpy.split(array,[index1,index2,......],axis)
axis默认值是0,表示垂直轴,如果值为1,表示水平的轴
注意:indices_or_sections -> [100,200]列表中有两个值,第一个值代表0:100,第二个值代表100:200,后面还有一个值200:会产生三个值,三个值需要三个变量来接收
# 例:
cat1,cat2,cat3 = np.split(cat,[100,200])
# show 是用于图形显示的,不给值就是空的
plt.imshow(cat1)
plt.show()
plt.imshow(cat2)
plt.show()
plt.ishow(cat3)
6.副本
所有赋值运算不会为ndarray的任何元素创建副本。对赋值后的对象的操作也对原来的对象生效
可用ndarray.copy()函数创建副本
7.ndarray的聚合函数
7.1 求和ndarray.sum()
ndarra.sum(axis),axis不写则为所有元素的求和,为0表示列求和,1表示行求和
axis 的值可以是一个元组,最后一维可以用-1来表示,-2可以用来表示倒数第二维度
7.2 最大、最小值
ndarray.max()/ndarray.min()
7.3 平均值
ndarray.mean()
7.4 如何将图片变为黑白
# 读取原图片
cat = imread('cat.jpg')
# 去掉图片第三维的值
cat2 = cat.mean(axis=2)
# camap='color' 黑白图片适用gray
plt.imshow(cat2,cmap='gray')
8.np.argmin Find index of minimum value 找到最小数的下标
np.argmax Find index of maximum value 找到最大数的下标
9.轴移动
moveaxis 可以将数组的轴移动到新的位置
numpy.moveaxis(a,source,destination)
- a:数组
- source: 要移动的轴的原始位置
- destination:要移动的轴的目标位置
# 例:
nd = np.array([[1,2,3],[1,2,3],[1,2,3]])
nd
# array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
np.moveaxis(nd1,0,1)
# array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
10. 轴交换
和moveaxis不同,swapaxes 可以用来交换数组的轴:
numpy.swapaxes(a,axis1,axis2)
- a:数组
- axis1:需要交换的轴1位置
- axis2:需要与轴1交换位置的轴1位置
11. 数组转置
transpose 类似于矩阵的转置,它可以将2维数组的水平轴和垂直轴交换:
numpy.transpose(a,axes=None)
- a: 数组
- axis: 该值默认为None,表示转置;如果有值,那么则按照值替换轴
Jupyter Notebook 有两种键盘输入模式。编辑模式,允许你往单元中键入代码或文本;这时的单元框线是绿色的。命令模式,键盘输入运行程序命令;这时的单元框线是灰色。