首页 > 解决方案 > 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()

旧图像(未经编辑) 旧图像(未经编辑)

新图像(编辑后) 新图像(编辑后)

标签: pythonnumpy

解决方案


我认为认为您可以通过检查 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

这是您的网格矩阵的示意图,其中,如果您遵循字母ABC等,您将获得通过网格元素的流动顺序。

但是,请注意,无论算法多么聪明,它都无法在两种可能的流程之间进行选择:

A, B, C, D, E, F, G, H, I, J,K

A, B, C, D, E, F, G, H, K, J,I

因此,我认为您必须自己明确记录序列,而不是从T网格中值的位置推断出它。

H在上面的例子中,任何算法都会在网格位置的歧义处停止


推荐阅读