np.where(cond,x,y)函数

本文详细解析了NumPy中的np.where()函数的工作原理及其用法。通过实例演示如何使用该函数根据条件选择不同的数值矩阵,并解释了其与Python三元表达式的相似之处。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在看特征提取的代码时遇到了np.where()函数,一脸懵逼,查了资料并没有发现什么有价值的内容。

知乎上逛了一圈略有收获。记录下来

np.where(condiction,x,y)这个函数的三个输入参数分别是条件(可以是矩阵),x,y数值矩阵用于返回值的选取:

语法类似于三元表达式x if condiction else y,当条件为真的时候返回x的值,条件为假时返回y的值。

光说不练假把式,没图说个金币


可以看到:np.where的语法类似[(x if condiction else y) for x,y,condiction in zip(x,y,condiction)]

这个又涉及到了zip的操作。取出各个列表(矩阵,元组)中对应位置的元素,组成新的元组,zip结果如下图:


这里设置condiction为cond = np.array([True,False,True])

满足Ture的时候取出上图的1.1,2.2.3.3中对应的数,这里可以看到zip后的元组,第一组的条件是Ture,所以取到x的第一个数1.1

然后是第二组,条件是False,所以会取到y,对应的是有False元素的那个元组,对应的元素是3.3(这里是3.299999...8);

然后是第三组,同理会取到第三个元组的第一个元素3.3(这里是3.299999...8)。

那么,np.where(condiction,x,y)返回的结果



两者是一样的。

不知道这样子讲各位是不是都清楚了。。

import deepxde as dde import matplotlib.pyplot as plt import numpy as np from deepxde.backend import torch import torch import os os.environ["DDE_BACKEND"] = "pytorch" geom = dde.geometry.Rectangle([0,0],[1,1]) #定义几何域,代表4个角点 timedomain = dde.geometry.TimeDomain(0,1.0) #定义时间域 geomtime = dde.geometry.GeometryXTime(geom,timedomain) #几何域与时间域的笛卡尔积 #定义pde损失函数 import numpy as np import numpy as np def k(x): x_coord = x[:, 0:1] cond1 = torch.lt(x_coord, 0.25) # x < 0.25 cond2 = torch.logical_and(torch.ge(x_coord, 0.25), torch.lt(x_coord, 0.50)) # 0.25 <= x < 0.50 cond3 = torch.logical_and(torch.ge(x_coord, 0.50), torch.lt(x_coord, 0.75)) # 0.50 <= x < 0.75 cond4 = torch.ge(x_coord, 0.75) # x >= 0.75 return torch.where(cond1, torch.tensor(1.0), torch.where(cond2, torch.tensor(2.0), torch.where(cond3, torch.tensor(3.0), torch.tensor(4.0)))) c=1 rho=1 def pde(x,y): dy_t = dde.grad.jacobian(y,x,i=0,j=2) dy_xx = dde.grad.hessian(y,x,i=0,j=0) dy_yy = dde.grad.hessian(y,x,i=1,j=1) return c * rho * dy_t - k(x) * (dy_xx + dy_yy) #定义边界条件 # 上边界,y=1 def boundary_t(x, on_boundary): return on_boundary and np.isclose(x[1], 1) # 下边界,y=0 def boundary_b(x, on_boundary): return on_boundary and np.isclose(x[1], 0) # 左边界,x=0 def boundary_l(x, on_boundary): return on_boundary and np.isclose(x[0], 0) # 右边界,x=1 def boundary_r(x, on_boundary): return on_boundary and np.isclose(x[0], 1) bc_t = dde.icbc.NeumannBC(geomtime, lambda x:0, boundary_t) bc_b = dde.icbc.NeumannBC(geomtime, lambda x:0, boundary_b) bc_l = dde.icbc.DirichletBC(geomtime, lambda x:10, boundary_l) bc_r = dde.icbc.DirichletBC(geomtime, lambda x:30, boundary_r) #定义初始条件 def init_func(x): return 0 ic = dde.icbc.IC(geomtime,init_func,lambda _,on_initial:on_initial,) #构建神经网络 data = dde.data.TimePDE( geomtime, pde, [bc_t,bc_b,bc_l,bc_r,ic], num_domain=8000, num_boundary=400, num_
03-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值