在numpy数组中搜索元素值并存储位置

2024-06-17 08:43:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个numpy数组,它表示三维模型中面的邻接关系。通常,第n行和第n列表示模型的第n个面。如果1位于矩阵的右上三角形中,则表示两个面之间的凸连接。如果1位于左下角的三角形中,则表示凹面连接。你知道吗

例如,在下面的矩阵中,面1和2、1和3、2和3之间存在凸连接,依此类推。你知道吗

       1   2   3   4   5   6

1   [[ 0.  1.  1.  0.  0.  0.]
2    [ 0.  0.  1.  1.  1.  1.]
3    [ 0.  0.  0.  0.  0.  0.]
4    [ 0.  0.  0.  0.  1.  0.]
5    [ 0.  0.  0.  0.  0.  0.]
6    [ 0.  0.  0.  0.  0.  0.]]

我想能够记录有多少凹和凸连接每个面有。你知道吗

即,面1具有:0个凹面和2个凸面连接

甚至可能记录下它们与哪些面相连。你知道吗

即,面1有:0个凹面和2个凸面(2,3)连接

到目前为止,我已经尝试使用np.nonzero()返回1的索引。但是,返回索引的格式似乎不太容易使用(行和列索引的单独数组:

(array([ 0,  0,  1,  1,  1,  1,  3]), array([ 1,  2,  2,  3,  4,  5, 
 4]))

有人能帮我找到一个更容易的方法来完成这项任务吗?谢谢


Tags: 模型numpy关系格式np记录矩阵数组
2条回答

试试这个:

import numpy as np


a=np.matrix([[0,1,1,0,0,0],
[ 0,0,1,1,1,1],
[ 0,0,0,0,0,0],
[ 0,0,0,0,1,0],
[ 0,0,0,0,0,0],
[ 0,0,0,0,0,0]]).astype(float)

concave={}
convex={}
for i,j in zip(np.nonzero(a)[0]+1,np.nonzero(a)[1]+1):
if j > i :
    if i not in convex.keys():
        convex[i]=[]
    if j not in convex.keys():
        convex[j]=[]
    convex[i].append(j)
    convex[j].append(i)
else :
    if i not in concave.keys():
        concave[i]=[]
    if j not in concave.keys():
        concave[j]=[]
    concave[i].append(j)
    concave[j].append(i)

print 'concave relations : {} and number of relations is {}'.format(concave,sum(len(v) for v in concave.values()))

print 'convex relations : {} and number of relations is {}'.format(convex,sum(len(v) for v in convex.values()))

给出结果:

concave relations : {} and number of relations is 0

convex relations : {1: [2, 3], 2: [1, 3, 4, 5, 6], 3: [1, 2], 4: [2, 5], 5: [2, 4], 6: [2]} and number of relations is 14

其中dictionary键是面的名称,键值是它的连接。你知道吗

逻辑是:

对于每个非零(i,j)

  • 如果i>;j,则j是面i的凹连接;i是面j的凹连接
  • 如果j>;i,则j是面i的凸连接,i是面j的凸连接
import numpy as np

A = np.array([[0,  1,  1,  0,  0,  0],
              [0,  0,  1,  1,  1,  1],
              [0,  0,  0,  0,  0,  0],
              [0,  0,  0,  0,  1,  0],
              [0,  0,  0,  0,  0,  0],
              [0,  0,  0,  0,  0,  0]])

convex = np.triu(A, 1)  # upper triangle
concave = np.tril(A, -1)  # lower triangle

convex_indices = list(zip(np.nonzero(convex)[0] + 1, np.nonzero(convex)[1] + 1))
concave_indices = list(zip(np.nonzero(concave)[0] + 1, np.nonzero(concave)[1] + 1))

num_convex = len(convex_indices)
num_concave = len(concave_indices)

print('There are {} convex connections between faces: {}'.format(num_convex, ', '.join(str(e) for e in convex_indices)))
print('There are {} concave connections between faces: {}'.format(num_concave, ', '.join(str(e) for e in concave_indices)))

# will print:
# There are 7 convex connections between faces: (1, 2), (1, 3), (2, 3), (2, 4), (2, 5), (2, 6), (4, 5)
# There are 0 concave connections between faces: 

相关问题 更多 >