NumPy

一、数据的维度


数据维度的python表示

一维数据:列表和集合类型

[3.14, 5.44 ,5.55] 有序
{3.14, 5.44 ,5.55} 无序

二维数据:列表类型
多维数据:列表类型

[ [3.14, 5.44 ,5.55],
  [3.14, 5.44 ,5.55]  ]

高维数据:字典类型或数据类型表示

dict = {
          "firstName":"Mace",
          "lastName":"Jin",
}

二、NumPy的数组对象:ndarray

一个强大的N维数组对象


numpy的引用

import numpy as np

例:计算A2+B3

import numpy as np

def npSum():
  a = np.array([0,1,2,3,4])
  b = np.array([9,8,7,6,5])
  c = a**2+b**3
  return c

print(npSum())

N维数组对象:ndarray

ndarray是一个多维数组对象,由两部分构成:

  • 实际的数据
  • 描述这些数据的元数据(数据纬度、数据类型等)
    ndarray数组一般要求所有元素类型相同(同质),数据下标从0开始。

np.array()生成一个ndarray数组
ndarray在程序中的别名是:array


In [1]:  a = np.array([[0,1,2,3,4],
   ...:               [9,8,7,6,5]])

In [2]:  a
Out[2]: 
array([[0, 1, 2, 3, 4],
       [9, 8, 7, 6, 5]])

In [3]: print(a)
[[0 1 2 3 4]
 [9 8 7 6 5]]

轴(axis):保存数据的纬度。
秩(rank):轴的数量。


ndarray对象的属性

属性 说明
.ndim 秩,即轴的数量或纬度的数量
.shape 对象的尺度,对于矩阵,n行m列
.size 对象元素的个数,相当于.shape中n*m的值
.dtype 对象的元素类型
.itemsize 对象中每个元素的大小,以字节为单位

ndarray的元素类型

数据类型 说明
bool 布尔类型,true或false
intc 与C语言中的int类型一致,一般是int32或int64
intp 用于索引的整数,与C语言中的ssize_t一致,int32或int64
int8 字节长度的整数,取值:【-128,127】
int16 16位长度的整数,取值:【-32768,32767】
int32 32位长度的整数,取值:【-231,231-1】
int64 64位长度的整数,取值:【-263,263-1】
uint8 8位无符号整数,取值【0,255】
uint16 16位无符号整数,取值【0,65535】
unit32 32位无符号整数,取值【0,232-1】
uint64 64位无符号整数,取值【2,264-1】
float16 16位半精度浮点数:1位符号位,5位指数位,10位尾数
float32 32位半精度浮点数:1位符号位,8位指数位,23位尾数
float64 16位半精度浮点数:1位符号位,11位指数位,52位尾数
complex64 复数类型,实部和虚部都是32位浮点数
complex128 复数类型,实部和虚部都是64位浮点数

三、ndarray数组的创建和变换


ndarray数组的创建方法

1.从python中的列表、元组等类型创建ndarray数组

x = np.array(list/tuple)
x = np.array(list/tuple, dtype=np.float32)

当np.array()不指定dtype时,numpy将根据数据情况关联一个dtype类型。


2.使用numpy中函数创建ndarray数组,如:arange,ones,zeros等。

函数 说明
np.arange(n) 类似range()函数,返回ndarray类型,元素从0到n-1
np.ones(shape) 根据shape生成一个全1数组,shape是元组类型
np.zeros(shape) 根据shape生成一个全0数组,shape是元组类型
np.full(shape,val) 根据shape生成一个数组,每个元素值都是val
np.eye(n) 创建一个正方的n*m单位矩阵,对角线为1,其余为0
np.ones_like(a) 根据数组a的形状生成一个全1数组
np.zeros_like(a) 根据数组a的形状生成一个全0数组
np.full_like(a,val) 根据数组a的形状生成一个数组,每个元素值都是val
np.arange(10)
Out[14]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

np.ones((3, 6))
Out[15]: 
array([[ 1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.]])

np.zeros((3, 6), dtype=np.int32)
Out[16]: 
array([[0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0]])

np.eye(5)
Out[17]: 
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.]])

x = np.ones((2, 3, 4))

print(x)
[[[ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]]

 [[ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]]]

x.shape
Out[20]: (2, 3, 4)

3.使用numpy中其他函数创建ndarray数组

函数 说明
np.linspace() 根据起止数据等间距地填充数据,形成数组
np.concatenate() 将两个或多个数组合并成一个新的数组
a = np.linspace(1, 10, 4)

a
Out[9]: array([  1.,   4.,   7.,  10.])

b = np.linspace(1, 10, 4, endpoint=False)

b
Out[11]: array([ 1.  ,  3.25,  5.5 ,  7.75])

c = np.concatenate((a,b))

c
Out[13]: array([  1.  ,   4.  ,   7.  ,  10.  ,   1.  ,   3.25,   5.5 ,   7.75])

ndarray数组的维度变换

方法 说明
.reshape(shape) 不改变数组元素,返回一个shape形状的数组,原数组不变
.resize(shape) 与.reshape()功能一致,但修改原数组
.swapaxes(ax1, ax2) 将数组n个维度中两个纬度进行调换
.flatten() 对数组进行降维,返回折叠后的一维数组,原数组不变
a = np.ones((2,3,4), dtype=np.int32)

a
Out[22]: 
array([[[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]],

       [[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]]])

a.reshape((3, 8))
Out[23]: 
array([[1, 1, 1, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1, 1, 1]])

a
Out[24]: 
array([[[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]],

       [[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]]])

a.resize((3, 8))

a
Out[26]: 
array([[1, 1, 1, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1, 1, 1]])

a.flatten()
Out[27]: 
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1])

a
Out[28]: 
array([[1, 1, 1, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1, 1, 1]])

b = a.flatten()

b
Out[30]: 
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1])

ndarray数组的类型变换

new_a = a.astype(new_type)

a = np.ones((2,3,4), dtype=np.int)

a
Out[32]: 
array([[[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]],

       [[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]]])

b = a.astype(np.float)

b
Out[34]: 
array([[[ 1.,  1.,  1.,  1.],
        [ 1.,  1.,  1.,  1.],
        [ 1.,  1.,  1.,  1.]],

       [[ 1.,  1.,  1.,  1.],
        [ 1.,  1.,  1.,  1.],
        [ 1.,  1.,  1.,  1.]]])

astype()方法一定会创建新的数组。


四、ndarray数组的操作

一维数组的索引和切片

a = np.array([9, 8, 7, 6, 5])

a[2]
Out[5]: 7

a[1 : 4 : 2]
Out[6]: array([8, 6])

多维数组的索引

a = np.arange(24).reshape((2,3,4))

a
Out[10]: 
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]]])

a[1, 2, 3]
Out[11]: 23

a[0, 1, 2]
Out[12]: 6

a[-1, -2, -3]
Out[13]: 17

多维数组的切片

a = np.arange(24).reshape((2,3,4))

a
Out[15]: 
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]]])

a[:, 1, -3]
Out[16]: array([ 5, 17])

a[:, 1:3, :]
Out[17]: 
array([[[ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[16, 17, 18, 19],
        [20, 21, 22, 23]]])

a[:, :, ::2]
Out[18]: 
array([[[ 0,  2],
        [ 4,  6],
        [ 8, 10]],

       [[12, 14],
        [16, 18],
        [20, 22]]])

五、ndarray数组的运算

数组与标量之间的运算

数组与标量的运算作用与数组的每一个元素

例:计算a与元素平均值的商

a = np.arange(24).reshape((2, 3, 4))

a
Out[3]: 
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]]])

a.mean()
Out[4]: 11.5

a = a / a.mean()

a
Out[6]: 
array([[[ 0.        ,  0.08695652,  0.17391304,  0.26086957],
        [ 0.34782609,  0.43478261,  0.52173913,  0.60869565],
        [ 0.69565217,  0.7826087 ,  0.86956522,  0.95652174]],

       [[ 1.04347826,  1.13043478,  1.2173913 ,  1.30434783],
        [ 1.39130435,  1.47826087,  1.56521739,  1.65217391],
        [ 1.73913043,  1.82608696,  1.91304348,  2.        ]]])

numpy一元函数对ndarray中的数据执行元素级运算的函数

函数 说明
np.abs(x) np.fabs(x) 计算数组各元素的绝对值
np.sqart(x) 计算数组各元素的平方根
np.square(x) 计算数组各元素的平方
np.log(x) np.log10(x) np.log2(x) 计算数组各元素的自然对数、10底对数和2底对数
np.ceil(x) np.floor(x) 计算数组各元素的ceiling值或floor值
np.rint(x) 计算数组各元素的四舍五入值
np.modf(x) 将数组各元素的小数和整数部分以两个独立数组形式返回
np.cos(x) np.cosh(x) np.sin(x) np.sinh(x) np.tan(x) np.tanh(x) 计算数组各元素的普通型和双曲型三角函数
np.sign(x) 计算数组各元素的符号值,1(+),0,-1(-)
np.exp(x) 计算数组各元素的指数值

numpy二元函数

函数 说明
+ - * / ** 两个数组各元素进行对应运算
np.maximun(x,y) np.fmax() 元素级的最大值
np.minimun(x,y) np.fmin() 元素级的最小值
np.mod(x,y) 元素级的模运算
np.copysign(x,y) 将数组y中各元素值的符号赋值给数组x对应元素
> < >= <= == != 算术比较,产生布尔型数组

六、数据的CSV文件存取

csv文件的储存

np.savetxt(frame,array,fmt='%.18e',delimiter=Nane)
  • frame:文件、字符串或产生器,可以是.gz或.bz2的压缩文件。
  • array:存入文件的数组。
  • fmt:写入文件的格式,例如:%d %.2f %.18e。
  • delimiter:分割字符串,默认是任何空格。
import numpy as np

a = np.arange(100).reshape(5, 20)

np.savetxt('a.csv', a, fmt='%d', delimiter=',')

打开的csv文件为:

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,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99

csv文件的读取

np.loadtxt(frame,dtype=np.float,delimiter=None,unpack=False)

  • frame:文件、字符串或产生器,可以是.gz或.bz2的压缩文件。
  • dtype:数据类型,可选。
  • delimiter:分割字符串,默认是任何空格。
  • unpack:如果True,读入属性将分别写入不同变量。
b = np.loadtxt('a.csv',delimiter=',')

b
Out[8]: 
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.,  64.,  65.,  66.,  67.,  68.,  69.,  70.,
         71.,  72.,  73.,  74.,  75.,  76.,  77.,  78.,  79.],
       [ 80.,  81.,  82.,  83.,  84.,  85.,  86.,  87.,  88.,  89.,  90.,
         91.,  92.,  93.,  94.,  95.,  96.,  97.,  98.,  99.]])

csv文件的局限性

  • csv只能有效存储一维和二维数组。
  • np.savetxt() np.loadtxt()只能有效存取一维和二维数组。

七、多维数据的存取

dat文件的储存

a.tofile(frame,sep='',format='%s')
  • frame:文件、字符串。
  • sep:数据分隔字符串,如果是空串,写入文件位二进制。
  • format:写入数据的格式。
a = np.arange(100).reshape(5, 10, 2)

a.tofile('b.dat', sep=',', format='%d')

打开dat文件

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,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99

dat文件的读取

np.fromfile(frame,dtype=float,count=-1,sep='')
  • frame:文件、字符串。
  • dtype:读取的数据类型。
  • count:读入元素个数,-1表示读入这个文件。
  • sep:数据分割字符串,如果是空串,写入文件为二进制。
c = np.fromfile('b.dat', dtype=np.int, sep=',')

c
Out[13]: 
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, 64, 65, 66, 67,
       68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
       85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99])

c = np.fromfile('b.dat', dtype=np.int, sep=',').reshape(5, 10, 2)

c
Out[15]: 
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],
        [64, 65],
        [66, 67],
        [68, 69],
        [70, 71],
        [72, 73],
        [74, 75],
        [76, 77],
        [78, 79]],

       [[80, 81],
        [82, 83],
        [84, 85],
        [86, 87],
        [88, 89],
        [90, 91],
        [92, 93],
        [94, 95],
        [96, 97],
        [98, 99]]])

numpy的便捷文件存取

np.svae(fname,array)或np.savez(fname,array)

  • frame:文件名,以.npy为拓展名,压缩拓展名为.npz
  • array:数组变量

np.load(fname)

  • frame:文件名,以.npy为拓展名,压缩拓展名为.npz
a = np.arange(100).reshape(5, 10, 2)

np.save('a.npy', a)

b = np.load('a.npy')

b
Out[19]: 
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],
        [64, 65],
        [66, 67],
        [68, 69],
        [70, 71],
        [72, 73],
        [74, 75],
        [76, 77],
        [78, 79]],

       [[80, 81],
        [82, 83],
        [84, 85],
        [86, 87],
        [88, 89],
        [90, 91],
        [92, 93],
        [94, 95],
        [96, 97],
        [98, 99]]])

八、numpy的随机数函数

numpy的random子库

np.random的随机数函数

函数 说明
rand(d0,...,dn) 根据d0-d创建随机数数组,浮点数,[0,1),均匀分布
randn(d0,...,dn) 根据d0-d创建随机数数组,标准正态分布
randint(low[,high,shape]) 根据shape创建随机整数或整数数组,范围是[low,high]
seed(s) 随机数种子,s是给定的种子值
import numpy as np

a = np.random.rand(3, 4, 5)

a
Out[3]: 
array([[[ 0.90054795,  0.71624173,  0.79112233,  0.32650461,  0.84619615],
        [ 0.44591395,  0.36828326,  0.76291491,  0.05558484,  0.12433055],
        [ 0.07534764,  0.8384202 ,  0.11716862,  0.47834772,  0.54191282],
        [ 0.2388626 ,  0.35017533,  0.25186745,  0.15812048,  0.41712066]],

       [[ 0.44394913,  0.91778932,  0.74652455,  0.91372906,  0.5342139 ],
        [ 0.3797729 ,  0.29731658,  0.21936994,  0.2333807 ,  0.7610462 ],
        [ 0.10821976,  0.04970031,  0.18018693,  0.11947951,  0.03711413],
        [ 0.97599868,  0.31263183,  0.52624546,  0.35155422,  0.5016402 ]],

       [[ 0.10641334,  0.5153669 ,  0.81933421,  0.44368124,  0.94465126],
        [ 0.31304866,  0.5379593 ,  0.19853566,  0.07185523,  0.36389356],
        [ 0.77520593,  0.74260994,  0.43217268,  0.26971247,  0.50587306],
        [ 0.69963568,  0.72048552,  0.97696634,  0.17689354,  0.02467841]]])

sn = np.random.randn(3, 4, 5)

sn
Out[5]: 
array([[[ 1.43524925, -0.01709225,  0.74060875,  0.10516008,  1.67940313],
        [-2.03931972,  0.4263534 , -0.18865956,  1.00951697, -0.17700187],
        [ 0.42265079, -0.56889342,  0.42843036,  0.1482564 , -0.99566954],
        [-1.89553322,  0.03920585, -0.53351015, -0.58438961, -2.62456031]],

       [[-1.23407899, -0.12697763, -0.13177403,  0.28296367,  1.2963296 ],
        [ 0.34109667, -1.16165189, -0.39677244, -0.32564733, -0.85124886],
        [ 0.27403558,  0.97343758, -0.80993655, -0.00463434, -1.87235953],
        [ 1.23773591,  0.05530726, -0.08753156, -0.25033669, -0.00327984]],

       [[ 1.07393704,  1.16992607, -2.91612329, -1.55628507,  0.83542134],
        [-0.83865651, -0.85258962,  1.04403901,  1.64369287,  0.19337034],
        [ 0.16633997, -0.09558055,  0.05283974, -1.31325106,  0.0460602 ],
        [ 0.52758321,  1.29531339, -0.92198878,  0.19512485,  0.1081831 ]]])

b = np.random.randint(100, 200, (3,4))

b
Out[7]: 
array([[153, 173, 139, 150],
       [190, 110, 180, 150],
       [178, 118, 174, 172]])

np.random.seed(10)

np.random.randint(100, 200, (3,4))
Out[9]: 
array([[109, 115, 164, 128],
       [189, 193, 129, 108],
       [173, 100, 140, 136]])

np.random.seed(10)

np.random.randint(100, 200, (3,4))
Out[11]: 
array([[109, 115, 164, 128],
       [189, 193, 129, 108],
       [173, 100, 140, 136]])

函数 说明
shuffle(a) 根据数组a的第1轴进行随机排列,改变数组x
permutation(a) 根据数组a的第一个轴产生一个新的乱序数组,不改变数组x
choice(a[,size,replace,p]) 从一维数组a中以概率p抽取元素,形成size形状新数组replace表示是否可以重用元素,默认位False
np.random.randint(100, 200, (3,4))
Out[11]: 
array([[109, 115, 164, 128],
       [189, 193, 129, 108],
       [173, 100, 140, 136]])

a = np.random.randint(100, 200, (3,4))

a
Out[13]: 
array([[116, 111, 154, 188],
       [162, 133, 172, 178],
       [149, 151, 154, 177]])

np.random.shuffle(a)

a
Out[15]: 
array([[116, 111, 154, 188],
       [149, 151, 154, 177],
       [162, 133, 172, 178]])

np.random.shuffle(a)

a
Out[17]: 
array([[162, 133, 172, 178],
       [116, 111, 154, 188],
       [149, 151, 154, 177]])
a = np.random.randint(100, 200, (3,4))

a
Out[23]: 
array([[177, 122, 123, 194],
       [111, 128, 174, 188],
       [109, 115, 118, 180]])


b = np.random.permutation(a)

b
Out[26]: 
array([[109, 115, 118, 180],
       [111, 128, 174, 188],
       [177, 122, 123, 194]])

a
Out[27]: 
array([[177, 122, 123, 194],
       [111, 128, 174, 188],
       [109, 115, 118, 180]])
b = np.random.randint(100, 200, (8,))

b
Out[30]: array([117, 146, 107, 175, 128, 133, 184, 196])

np.random.choice(b, (3, 2))
Out[31]: 
array([[117, 128],
       [133, 128],
       [196, 117]])

np.random.choice(b, (3, 2), replace=False)
Out[32]: 
array([[133, 175],
       [146, 196],
       [184, 128]])

np.random.choice(b, (3, 2), p=b/np.sum(b))
Out[33]: 
array([[196, 107],
       [146, 196],
       [133, 133]])

函数 说明
uniform(low,high,size) 产生具有均匀分布的数组,low起始值,high结束值,size形状
normal(loc,scale,size) 产生具有正态分布的数组,loc均值,scale标准差,size形状
poisson(lam,size) 产生具有泊松分布的数组,lam随机事件发生率值,size形状
u = np.random.uniform(0, 10, (3,4))

u
Out[35]: 
array([[ 4.36353698,  3.56250327,  5.87130925,  1.49471337],
       [ 1.71238598,  3.97164523,  6.37951564,  3.72519952],
       [ 0.02406761,  5.48816356,  1.26971841,  0.79792681]])

n = np.random.normal(10, 5, (3,4))

n
Out[37]: 
array([[ 13.57941572,   4.07115727,   6.81836048,   6.94593078],
       [  3.40304302,   7.19135792,  11.02692287,   5.23319662],
       [ 11.60758976,   2.39530663,  -0.80726459,  11.72656647]])

九、numpy的统计函数

函数 说明
sum(a,axis=None) 根据给定轴axis计算数组a相关元素之和,axis整数或元组
mean(a,axis=None) 根据给定轴axis计算数组a相关元素的期望,axis整数或元组
average(a,axis=None,weights=None) 根据给定轴axis计算数组a相关元素的加权平均值
std(a,axis=None) 根据给定轴axis计算数组a相关元素的标准差
var(a,axis=None) 根据给定轴axis计算数组a相关元素的方差
a = np.arange(15).reshape(3, 5)

a
Out[39]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

np.sum(a)
Out[40]: 105

np.mean(a)
Out[41]: 7.0

np.mean(a, axis=1)
Out[42]: array([  2.,   7.,  12.])

np.mean(a, axis=0)
Out[43]: array([ 5.,  6.,  7.,  8.,  9.])

np.average(a, axis=0, weights=[10, 5, 1])
Out[44]: array([ 2.1875,  3.1875,  4.1875,  5.1875,  6.1875])

np.std(a)
Out[45]: 4.3204937989385739

np.var(a)
Out[46]: 18.666666666666668

函数 说明
min(a) max(a) 计算数组a中元素的最小值、最大值
argmin(a) argmax(a) 计算数组a中元素的最小值、最大值的降一维后下标
unravel_index(index,shape) 根据shape将一维下标index转换成多维下标
ptp(a) 计算数组a中元素最大值与最小值的差
median(a) 计算数组a中元素的中位数(中值)
b = np.arange(15,0,-1).reshape(3,5)

b
Out[48]: 
array([[15, 14, 13, 12, 11],
       [10,  9,  8,  7,  6],
       [ 5,  4,  3,  2,  1]])

np.max(b)
Out[49]: 15

np.argmax(b)
Out[50]: 0

np.unravel_index(np.argmax(b), b.shape)
Out[51]: (0, 0)

np.ptp(b)
Out[52]: 14

np.median(b)
Out[53]: 8.0

十、numpy的梯度函数

np.gradient(f)

计算数组f中元素的梯度,当f为多维时,返回每个纬度梯度。

a = np.random.randint(0, 20, (5))

a
Out[12]: array([16,  9, 11,  6,  7])

np.gradient(a)
Out[13]: array([-7. , -2.5, -1.5, -2. ,  1. ])

b = np.random.randint(0, 50, (3, 5))

b
Out[15]: 
array([[13, 46, 38,  8, 47],
       [22, 13,  1, 45, 43],
       [48, 23,  5, 29, 47]])

np.gradient(b)
Out[16]: 
[array([[  9. , -33. , -37. ,  37. ,  -4. ],
        [ 17.5, -11.5, -16.5,  10.5,   0. ],
        [ 26. ,  10. ,   4. , -16. ,   4. ]]),
 array([[ 33. ,  12.5, -19. ,   4.5,  39. ],
        [ -9. , -10.5,  16. ,  21. ,  -2. ],
        [-25. , -21.5,   3. ,  21. ,  18. ]])]

十一、图像的数组表示

图像的RGB色彩模式

  • 取值:0-255

PIL库

from PIL import Image

Image是PIL库中代表一个图像的类(对象)

from PIL import Image

import numpy as np

a = np.array(Image.open("D:/py/el.jpg"))

print(a.shape, a.dtype)
(375, 500, 3) uint8

b = [255, 255, 255] - a

im = Image.fromarray(b.astype('uint8'))

im.save("D:/py/el2.jpg")
el.jpg

el2.jpg

from PIL import Image

import numpy as np

a = np.array(Image.open("D:/py/el.jpg").convert('L'))

b = 255 - a

im = Image.fromarray(b.astype('uint8'))

im.save("D:/py/el3.jpg")

el3.jpg

from PIL import Image

import numpy as np

a = np.array(Image.open("D:/py/el.jpg").convert('L'))

c = (100/255)*a + 150 #区间变换

im = Image.fromarray(c.astype('uint8'))

im.save("D:/py/el4.jpg")

el4.jpg

from PIL import Image

import numpy as np

a = np.asarray(Image.open("D:/py/pd.jpg").convert('L')).astype('float')

depth = 10

grad = np.gradient(a)

grad_x, grad_y = grad

grad_x = grad_x*depth/100.

grad_y = grad_y*depth/100.

A = np.sqrt(grad_x**2 + grad_y**2 + 1.)

uni_x = grad_x/A

uni_y = grad_y/A

uni_z = 1./A

vec_el = np.pi/2.2

vec_az = np.pi/4.

dx = np.cos(vec_el)*np.cos(vec_az)

dy = np.cos(vec_el)*np.sin(vec_az)

dz = np.sin(vec_el)

b = 255*(dx*uni_x + dy*uni_y + dz*uni_z)

b = b.clip(0, 255)

im = Image.fromarray(b.astype('uint8'))

im.save("D:/py/pdHD.jpg")
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容