python - Python:从 np.where() 重新排列索引
问题描述
我想重新排列使用 np.where 创建的元组中的索引。这样做的原因是,我想将值应用于预先选择的网格中的一些特殊位置(管道)。这些值应适用于流动方向。流动方向定义为从左上角到左下角 = 从 (3,0) 到 (3,6) 到 (7,6) 到 (7,0)。目前,索引元组的顺序ind
是根据索引的自动排序。这导致了下图,其中1:10
正确应用了值,但 11:17 显然是相反的顺序。
有没有更好的方法来获取索引或者我如何重新排列元组以便将值应用于流动方向?
import numpy as np
import matplotlib.pyplot as plt
# mesh size
nx, ny = 10, 10
# special positions
sx1, sx2, sy = .3, .7, .7
T = 1
# create mesh
u0 = np.zeros((nx, ny))
# assign values to mesh
u0[int(nx*sx1), 0:int(ny*sy)] = T
u0[int(nx*sx2), 0:int(ny*sy)] = T
u0[int(nx*sx1+1):int(nx*sx2), int(ny*sy-1)] = T
# get indices of special positions
ind = np.where(u0 == T)
# EDIT: hand code sequence
length = len(u0[int(nx*sx2), 0:int(ny*sy)])
ind[0][-length:] = np.flip(ind[0][-length:])
ind[1][-length:] = np.flip(ind[1][-length:])
# apply new values on special positions
u0[ind] = np.arange(1, len(ind[1])+1,1)
fig, ax = plt.subplots()
fig = ax.imshow(u0, cmap=plt.get_cmap('RdBu_r'))
ax.figure.colorbar(fig)
plt.show()
解决方案
我认为认为您可以通过检查 tuple 的内容从算法上推断出网格点的正确“流序列”是一种谬论ind
。
这是一个说明原因的示例:
0 0 0 0 0 0 0 0 0 0
A B C D E 0 0 0 0 0
0 0 0 0 F 0 0 0 0 0
0 0 0 0 G 0 0 0 0 0
0 0 0 I H 0 0 0 0 0
0 0 0 J K 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
这是您的网格矩阵的示意图,其中,如果您遵循字母A
、B
、C
等,您将获得通过网格元素的流动顺序。
但是,请注意,无论算法多么聪明,它都无法在两种可能的流程之间进行选择:
A
, B
, C
, D
, E
, F
, G
, H
, I
, J
,K
和
A
, B
, C
, D
, E
, F
, G
, H
, K
, J
,I
因此,我认为您必须自己明确记录序列,而不是从T
网格中值的位置推断出它。
H
在上面的例子中,任何算法都会在网格位置的歧义处停止
推荐阅读
- python - 在 groupby 之后基于第二列中的第一个最大值的一列的值
- node.js - 如何在 MS Teams 中使用轮播卡显示分页
- python - Python / Flask:ImportError:无法从'core'导入名称'app'
- javascript - 使用 Javascript 在列表中插入新项目时,我得到一个空值
- orm - TypeORM 不在列上添加外键
- c++ - 使用来自 c++ DLL 的函数
- git - 无法执行 Ansible 脚本以从 git 获取代码并将其推送到多个服务器
- django - /config/list_enseignant/ 处的 NoReverseMatch
- javascript - 在 {} 中解压缩对象
- python - 使用 selenium 从元素获取 src