【问题标题】:Create a Numpy array representing connections in a network创建一个表示网络中连接的 Numpy 数组
【发布时间】:2015-01-21 16:41:19
【问题描述】:

假设我有一个描述节点之间网络链接的数组:

array([[ 1.,  2.],
       [ 2.,  3.],
       [ 3.,  4.]])

这将是一个线性 4 节点网络,具有从节点 1 到节点 2 的链接,依此类推..

将此信息转换为以下格式的数组的最佳方法是什么?

array([[ 0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.]])

然后列号表示“到节点”,行表示“从节点”。

另一个例子是:

array([[ 1.,  2.],
       [ 2.,  3.],
       [ 2.,  4.]]) 

给予

array([[ 0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  1.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])

【问题讨论】:

  • float 可能不是存储节点 ID 的最佳变量类型。
  • @eumiro 公平点,可能应该使用整数或布尔值,但这可以说明我想要什么。
  • 基于 0 的节点 ID 也会让它更简单一些
  • @njzk2 是的,虽然由于源数据我坚持使用基于 1 的方法 - 可以让 -1 成为第一步...

标签: python arrays numpy


【解决方案1】:

节点 ID 应该是整数。 numpy 中的行和列也是从零开始编号的,所以我们必须在每个维度中减去一个:

import numpy as np

conns = np.array([[ 1,  2],
                  [ 2,  3],
                  [ 3,  4]])
net = np.zeros((conns.max(), conns.max()), dtype=int)

# two possibilities:

# if you need the number of connections:
for conn in conns:
    net[conn[0]-1, conn[1]-1] += 1

# if you just need a 1 for existing connection(s):
net[conns[:,0]-1, conns[:,1]-1] = 1

【讨论】:

  • 不是循环,你不能做net[conns[:,0]-1, conns[:,1]-1] = 1吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-28
  • 2017-12-30
  • 2012-04-04
  • 2017-12-27
  • 1970-01-01
  • 2021-10-26
相关资源
最近更新 更多