python之numpy库知识大全-爱代码爱编程 (2024)

#A,B是一维数组,计算A^2+B^3#方法一# a=[0,1,2,3,4]# b=[5,6,7,8,9]# c=[]# for i in range(0,5):# c.append(a[i]**2+b[i]**3)# print(c)#方法二:import numpy as npa=[0,1,2,3,4]b=[5,6,7,8,9]a_array=np.array(a)b_array=np.array(b)c=a_array**2+b_array**3print(c)

数组的优势:

数组对象可以去掉元素间运算所需的循环,使一维向量更像单个数据

设置专门的数组对象,经过优化,可以提升这类应用的运算速度

观察:科学计算中,一个维度所有数据的类型往往相同

数组对象采用相同的数据类型,有助于节省运算和存储空间

NumPy库处理的最基础数据类型是由

同种元素构成的多维数组(ndarry)

简称“数组”。

numpy数组的维数称为,每一个线

性的数组称为

同一个numpy数组中所有元素的类型

一般是相同的。

import numpy as npa_array=np.arange(9).reshape((3,3))print(a_array)print(np.sum(a_array,axis=0)) #axis=0表示列print(np.max(a_array,axis=1)) #axis=1表示行

E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/2.py"
[[0 1 2]
[3 4 5]
[6 7 8]]
[ 9 12 15]
[2 5 8]

Process finished with exit code 0

2.数组的创建

数组创建的主要方式

Python中的列表、元组等类型创建ndarray数组

使用NumPy中函数创建ndarray数组,如:arange, ones, zeros

从字节流(raw bytes)中创建ndarray数组

从文件中读取特定格式,创建ndarray数组

内置数据结构创建数组

基本格式:

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

实例:

import numpy as npa_array=np.array(((1,2),(3,4)))b_array=np.array([[1.5,2],[2.5,3]])print(a_array)print(b_array)结果:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/3.py"[[1 2] [3 4]][[1.5 2. ] [2.5 3. ]]Process finished with exit code 0

数组元素的类型(一)

python之numpy库知识大全-爱代码爱编程 (1)

数组元素的类型(二)

python之numpy库知识大全-爱代码爱编程 (2)

ndarray为什么要支持这么多种元素类型?

Python语法仅支持整数、浮点数和复数3种类型

Ndarry的优势

科学计算涉及数据较多,对存储和性能都有较高要求

对元素类型精细定义,有助于NumPy合理使用存储空间并优化性能

对元素类型精细定义,有助于程序员对程序规模有合理评估

常用函数创建数组

python之numpy库知识大全-爱代码爱编程 (3)

实例:

import numpy as npa_array=np.arange(10)print(a_array)b_array=np.ones((3,4))print(b_array)c_array=np.ones((3,4),dtype=np.int32)print(c_array)d_array=np.zeros((3,4),dtype=np.int32)print(d_array)e_array=np.eye(4,dtype=np.int32)print(e_array)f_array=np.full((3,4),6)print(f_array)结果:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/4.py"[0 1 2 3 4 5 6 7 8 9][[1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]][[1 1 1 1] [1 1 1 1] [1 1 1 1]][[0 0 0 0] [0 0 0 0] [0 0 0 0]][[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]][[6 6 6 6] [6 6 6 6] [6 6 6 6]]Process finished with exit code 0

已知尺度大小创建数组

python之numpy库知识大全-爱代码爱编程 (4)

实例:

import numpy as npa=np.arange(9).reshape((3,3))print(a)b=np.ones_like(a)c=np.zeros_like(a)d=np.full_like(a,6)print(f'b={b}')print(f'c={c}')print(f'd={d}')结果:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/5.py"[[0 1 2] [3 4 5] [6 7 8]]b=[[1 1 1] [1 1 1] [1 1 1]]c=[[0 0 0] [0 0 0] [0 0 0]]d=[[6 6 6] [6 6 6] [6 6 6]]Process finished with exit code 0

数组对象的属性

python之numpy库知识大全-爱代码爱编程 (5)

实例:

import numpy as npa=np.array([[1,2,3,4,5],[6,7,8,9,10]])b=np.array([6,66,666])c=np.array([[6,7,77]])print(a.ndim) #数组的维度print(a.shape) #数组的结构print(b.shape)print(c.shape)print(a.size) #数组的大小print(a.dtype) #数组的类型print(a.itemsize) #数组中每个元素所占的类型结果:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/6.py"2(2, 5)(3,)(1, 3)10int324Process finished with exit code 0

数组维度的改变

python之numpy库知识大全-爱代码爱编程 (6)

实例:

import numpy as npa=np.ones((2,3,4),dtype=np.int32) #两个三行四列的数组,类型为int32print(a)b=a.reshape((3,8))print(b)# c=a.resize((3,8))# print(c)d=a.reshape((4,-1)) #4行n列,-1表示不知道有多少列print(d)e=a.flatten()print(e) #降维,降成一维数组(平铺)f=a.swapaxes(1,2)print(f) #a中的两个三行四列变为两个四行三列g=b.transpose()print(g) #b中的3*8数组转置为8*3数组结果:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/7.py"[[[1 1 1 1] [1 1 1 1] [1 1 1 1]] [[1 1 1 1] [1 1 1 1] [1 1 1 1]]][[1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1]][[1 1 1 1 1 1] [1 1 1 1 1 1] [1 1 1 1 1 1] [1 1 1 1 1 1]][1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1][[[1 1 1] [1 1 1] [1 1 1] [1 1 1]] [[1 1 1] [1 1 1] [1 1 1] [1 1 1]]][[1 1 1] [1 1 1] [1 1 1] [1 1 1] [1 1 1] [1 1 1] [1 1 1] [1 1 1]]Process finished with exit code 0

将一维数组转化为列表:

array.tolist()

实例:

import numpy as npprint(np.arange(10).reshape(2,5))print(np.arange(10).reshape(2,5).tolist())结果:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/8.py"[[0 1 2 3 4] [5 6 7 8 9]][[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]Process finished with exit code 0

数组的组合操作

import numpy as npa=np.arange(9).reshape((3,3))b=np.arange(10,19).reshape((3,3))print(a)print(b)c=np.hstack((a,b)) #水平组合d=np.vstack((a,b)) #垂直组合e=np.dstack((a,b)) #深度组合print(c)print(d)print(e)结果:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/9.py"[[0 1 2] [3 4 5] [6 7 8]][[10 11 12] [13 14 15] [16 17 18]][[ 0 1 2 10 11 12] [ 3 4 5 13 14 15] [ 6 7 8 16 17 18]][[ 0 1 2] [ 3 4 5] [ 6 7 8] [10 11 12] [13 14 15] [16 17 18]][[[ 0 10] [ 1 11] [ 2 12]] [[ 3 13] [ 4 14] [ 5 15]] [[ 6 16] [ 7 17] [ 8 18]]]Process finished with exit code 0

数组的分割操作

import numpy as npa=np.arange(9).reshape(3,3)# print(a)b=np.split(a,3,axis=1) #与b=np.hsplit(a,3)功能相同,垂直分割c=np.split(a,3,axis=0) #与c=np.vsplit(a,3)功能相同,平行分割print(b)print(c)结果:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/数组分割.py"[array([[0], [3], [6]]), array([[1], [4], [7]]), array([[2], [5], [8]])][array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]Process finished with exit code 0

3.数组的索引

一维数组的基本索引

import numpy as npa=np.arange(9)print(a)print(a[1]) #索引print(a[1:3]) #切片print(a[1:9:2]) #切片,每隔两个..b=a[:] #数组是一个可变对象b[-1]=9print(a)print(b)c=a[1:3].copy() #数组切片是原始数组的视图,数据不会被复制,视图上的任何修改都会直接反映到源数组。c[-1]=10print(a)print(c)输出:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/基本索引.py"[0 1 2 3 4 5 6 7 8]1[1 2][1 3 5 7][0 1 2 3 4 5 6 7 9][0 1 2 3 4 5 6 7 9][0 1 2 3 4 5 6 7 9][ 1 10]Process finished with exit code 0

二维数组的切片索引

import numpy as npa=np.arange(9).reshape(3,3)b=np.arange(12).reshape(3,4)print(a)print(a[1,2]) #取第二行,第三列的元素print(a[1,:]) #取第二行的元素print(a[:,1]) #取第二列的元素print(a[1:,1:]) #取第二行到最后一行,第二列到最后一列的所有元素print(a[:1]) #取第一行的所有元素print(a[1:]) #取除了第一行的所有元素输出:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/二维数组索引.py"[[0 1 2] [3 4 5] [6 7 8]]5[3 4 5][1 4 7][[4 5] [7 8]][[0 1 2]][[3 4 5] [6 7 8]]Process finished with exit code 0

二维数组增删改查操作

import numpy as npa=np.arange(9).reshape(3,3)print(a)b=np.insert(a,1,[6,6,6],0) #增:np.insert(arr, obj, values, axis=None) # obj为索引,在该行(列)之前插入valuesprint(b) #axis:默认为 None,返回的是一维数组;当 axis =0 时,追加的值会被添加到行,而列数保持不变,若 axis=1 则与其恰好相反c=np.delete(a,1,0) #numpy.delete(arr, obj, axis) axis=0对行进行操作 axis=1对列进行操作print(c)d=np.append(a,[[666,666,666]],0) #numpy.append(arr, values, axis=None) 在最后一行进行添加操作(沿轴0)print(d)e=np.append(a,[[11,22],[44,55],[77,88]],1) #沿轴1 进行列操作print(e)f=np.where(a==5) #查找元素5所在的行和列,并返回元素的类型print(f)输出:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/增删改查操作.py"[[0 1 2] [3 4 5] [6 7 8]][[0 1 2] [6 6 6] [3 4 5] [6 7 8]][[0 1 2] [6 7 8]][[ 0 1 2] [ 3 4 5] [ 6 7 8] [666 666 666]][[ 0 1 2 11 22] [ 3 4 5 44 55] [ 6 7 8 77 88]](array([1], dtype=int64), array([2], dtype=int64))Process finished with exit code 0

4.数组的矢量化

矢量化(vectorization):数组不用编写循环即可实现对数据执行批量运算。

大小相等的数组之间的任何算数运算都将应用至元素级

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

import numpy as npa=np.arange(1,9).reshape(2,4)print(a)print(a*a)print(1/a)输出:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/数组的矢量化.py"[[1 2 3 4] [5 6 7 8]][[ 1 4 9 16] [25 36 49 64]][[1. 0.5 0.33333333 0.25 ] [0.2 0.16666667 0.14285714 0.125 ]]Process finished with exit code 0

布尔型索引

import numpy as npdata=np.random.randn(7,4)data_bool=(data>=0)print(data)data[data<0]=0print(data)print(data_bool.sum()) #大于等于0的个数print(data_bool.any()) #有大于0的数print(data_bool.all()) #是否均大于0输出:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/布尔型索引.py"[[ 1.63811042 1.54445329 -0.50855556 0.66308194] [ 0.12879628 -2.03570072 0.01191314 -0.06932157] [ 0.33557615 0.71268317 -0.68343232 -0.63477468] [-1.39206954 1.00314553 -0.34956396 0.1029916 ] [ 2.70711258 1.42974385 -0.41166823 -1.51228186] [-0.21329145 -0.80455934 -1.24286032 0.8425069 ] [-0.03085091 1.29717035 -0.77213397 -1.98034943]][[1.63811042 1.54445329 0. 0.66308194] [0.12879628 0. 0.01191314 0. ] [0.33557615 0.71268317 0. 0. ] [0. 1.00314553 0. 0.1029916 ] [2.70711258 1.42974385 0. 0. ] [0. 0. 0. 0.8425069 ] [0. 1.29717035 0. 0. ]]13TrueFalseProcess finished with exit code 0

一元算数函数

python之numpy库知识大全-爱代码爱编程 (7)

python之numpy库知识大全-爱代码爱编程 (8)

import numpy as npa=np.arange(1,10).reshape(3,3)b=np.array([[-1,-2,-3],[-4,-5,-6]])print(a,'\n')print(np.sqrt(a),'\n') #求平方根print(np.modf(a),'\n') #计算print(np.abs(b),'\n') #计算各个元素的绝对值,功能和np.fabs()相同print(np.square(a),'\n') #计算各个元素的平方print(np.log(a),'\n') #取对数,相当于loge,print(np.log10(a),'\n') #求10底对数print(np.log2(a),'\n') #求2底对数print(np.ceil(a),'\n') #向上取整print(np.floor(a),'\n') #向下取整print(np.rint(a),'\n') #计算元素的四舍五入值print(np.exp(a),'\n') #计算各个元素的指数值outer:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/一元算术函数.py"[[1 2 3] [4 5 6] [7 8 9]] [[1. 1.41421356 1.73205081] [2. 2.23606798 2.44948974] [2.64575131 2.82842712 3. ]] (array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]), array([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]])) [[1 2 3] [4 5 6]] [[ 1 4 9] [16 25 36] [49 64 81]] [[0. 0.69314718 1.09861229] [1.38629436 1.60943791 1.79175947] [1.94591015 2.07944154 2.19722458]] [[0. 0.30103 0.47712125] [0.60205999 0.69897 0.77815125] [0.84509804 0.90308999 0.95424251]] [[0. 1. 1.5849625 ] [2. 2.32192809 2.5849625 ] [2.80735492 3. 3.169925 ]] [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.]] [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.]] [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.]] [[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]] Process finished with exit code 0

二元运算函数

python之numpy库知识大全-爱代码爱编程 (9)

import numpy as npa=np.arange(1,10).reshape(3,3)b=np.sqrt(a)print(np.fmax(a,b)) #计算a,b数组最大值 相当于np.maximum(a,b)print(np.fmin(a,b)) #计算最小值 相当于np.minimum(a,b)print(np.mod(a,b)) #模运算求余数print(a>b) #算数比较,产生布尔型数组outer:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/二元算术函数.py"[[1. 2. 3.] [4. 5. 6.] [7. 8. 9.]][[1. 1.41421356 1.73205081] [2. 2.23606798 2.44948974] [2.64575131 2.82842712 3. ]][[0. 0.58578644 1.26794919] [0. 0.52786405 1.10102051] [1.70849738 2.34314575 0. ]][[False True True] [ True True True] [ True True True]]Process finished with exit code 0

二元函数--meshgrid函数

适用于生成网格型数据,可以接受两个一维数组生成两个二维矩阵,对应两个数组

中所有的(x,y)对。

import numpy as npx=np.array([0,1,2,3])y=np.array([0,1,2,3,4])xx,yy=np.meshgrid(x,y)print(xx) #以x为行,共len(y)=5行的向量print('---------------')print(yy) #以y为列,共len(x)=4列的向量outer:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/二元函数--meshgrid函数.py"[[0 1 2 3] [0 1 2 3] [0 1 2 3] [0 1 2 3] [0 1 2 3]]---------------[[0 0 0 0] [1 1 1 1] [2 2 2 2] [3 3 3 3] [4 4 4 4]]Process finished with exit code 0

三元函数

numpy.where函数是三元表达式x if condition else y的矢量化版本。

import numpy as npa=np.arange(-3,6).reshape(3,3)print(a)print(np.where(a>0,1,-1)) # np.where(condition,x,y) 相当于 x if condition else y #if 满足condition 则输出x,否则输出youter:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/三元函数where.py"[[-3 -2 -1] [ 0 1 2] [ 3 4 5]][[-1 -1 -1] [-1 1 1] [ 1 1 1]]Process finished with exit code 0

集合逻辑

NumPy提供了一些针对一维ndarray的基本集合运算,其中np.unique用于找出数组中

的唯一值并返回已排序的结果。

python之numpy库知识大全-爱代码爱编程 (10)

import numpy as npa=np.arange(-1,8).reshape(3,3)b=np.arange(-5,4).reshape(3,3)print(a)print(b)print(np.intersect1d(a,b))outer:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/第四节.py"[[-1 0 1] [ 2 3 4] [ 5 6 7]][[-5 -4 -3] [-2 -1 0] [ 1 2 3]][-1 0 1 2 3]Process finished with exit code 0

统计函数

通过数组上的一组数学函数对整个数组或某个轴向的数据进行统计计算。聚合计算

aggregation,通常叫做约简(reduction))

python之numpy库知识大全-爱代码爱编程 (11)

import numpy as npa=np.arange(-1,8).reshape(3,3)b=np.arange(-5,4).reshape(3,3)print(a)print(b)print(np.intersect1d(a,b))print(np.sum(a))print(np.c*msum(a,axis=0)) #元素(按列)逐个相加(每列求和)print(np.c*msum(a,axis=1)) #元素(按行)逐个相加(每行求和)print(np.c*msum(a)) #所有元素逐个相加outer:E:\anaconda\python.exe "E:/pythonProject1 hello world/Numpy/第四节.py"[[-1 0 1] [ 2 3 4] [ 5 6 7]][[-5 -4 -3] [-2 -1 0] [ 1 2 3]][-1 0 1 2 3]27[[-1 0 1] [ 1 3 5] [ 6 9 12]][[-1 -1 0] [ 2 5 9] [ 5 11 18]][-1 -1 0 2 5 9 14 20 27]Process finished with exit code 0

常用分布函数的随机数

python之numpy库知识大全-爱代码爱编程 (12)

线性代数

线性代数是任何数组库的重要组成部分,linalg模块中有标准的矩阵分解运算以及诸

如求逆和行列式之类的函数。

python之numpy库知识大全-爱代码爱编程 (13)

专用函数

sort函数返回排序后的数组

argsort函数返回输入数组排序后的下标;

lexsort函数根据键值的字典序进行排序;

例如:ind = np.lexsort((b,a)) # Sort by a, then by b

ndarray类的sort方法可对数组进行原地排序;

msort函数沿着第一个轴排序;

sort_complex函数对复数按照先实部后虚部的顺序进行排序。

5.Numpy文件操作

tofile()fromfile()

数据以二进制格式写进文件,事先知道存入文件时数组的维度和元

素类型 。

save()load()

用的二进制格式保存数据,它们会自动处理元素类型和形状等信

息,以.npy.npz为扩展名。

savetxt()loadtxt()

读写1维和2维数组的文本文件

读取文件

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

写入文件

np.savetxt(frame, array, fmt='%.18e', delimiter=None)

python之numpy库知识大全-爱代码爱编程 (14)

python之numpy库知识大全-爱代码爱编程 (2024)

References

Top Articles
Ixali Beast Tribe Guide and Rewards
All A Realm Reborn (ARR) Hunt Mark locations in Final Fantasy XIV
Tears Of The Fallen Moon Bdo
Samsung 9C8
Exploring the Northern Michigan Craigslist: Your Gateway to Community and Bargains - Derby Telegraph
Abc Order Hs Login
80 For Brady Showtimes Near Brenden Theatres Kingman 4
Brazos County Jail Times Newspaper
2 værelses hus i Ejby
Shaw Centre for the Salish Sea — Eight Arms, Eight Interesting Facts: World Octopus Day
5417873087
Super Nash Bros Tft
[PDF] JO S T OR - Free Download PDF
Cherry Spa Madison
Nyu Paralegal Program
Asoiaf Spacebattles
Binny Arcot
Bones And All Showtimes Near Tucson Spectrum 18
A Flame Extinguished Wow Bugged
Craigslist Yamhill
Hood County Buy Sell And Trade
Dickinson Jewelers Prince Frederick Md
Highplainsobserverperryton
159R Bus Schedule Pdf
Starter Blocked Freightliner Cascadia
Cool Motion matras kopen bij M line? Sleep well. Move better
Craigslist Caldwell Id
Cardaras Logan Ohio
8663081159
Algebra 1 Unit 1 Interactive Notebook Pages – The Foundations of Algebra
Craigslist Tampa: Your Ultimate Guide To Online Classifieds
85085 1" Drive Electronic Torque Wrench 150-1000 ft/lbs. - Gearwrench
Rugrats in Paris: The Movie | Rotten Tomatoes
Rate My Naughty.com
Meagan Flaherty Tells Kelli Off
Simple Simon's Pizza Lone Jack Menu
Cornerstone Okta T Mobile
How Did Laura Get Narally Pregnant
Intelligent intranet overview - SharePoint in Microsoft 365
Heatinghelp The Wall
Lucky Money Strain
Topic: Prisoners in the United States
Apphomie.com Download
Bella Poarch Husband: A Deep Dive Into Her Relationship And Personal Life
Southwest Flight 238
Gizmo Ripple Tank Answer Key
Swag Codes: The Ultimate Guide to Boosting Your Swagbucks Earnings - Ricky Spears
Unblocked Games 67 Ez
Niw 一亩三分地
Horoskopi Koha
Upgrading Fedora Linux to a New Release
Latest Posts
Article information

Author: Kerri Lueilwitz

Last Updated:

Views: 6133

Rating: 4.7 / 5 (47 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Kerri Lueilwitz

Birthday: 1992-10-31

Address: Suite 878 3699 Chantelle Roads, Colebury, NC 68599

Phone: +6111989609516

Job: Chief Farming Manager

Hobby: Mycology, Stone skipping, Dowsing, Whittling, Taxidermy, Sand art, Roller skating

Introduction: My name is Kerri Lueilwitz, I am a courageous, gentle, quaint, thankful, outstanding, brave, vast person who loves writing and wants to share my knowledge and understanding with you.