Python转换矩阵与关系列表

时间:2017-08-02 16:27:19

标签: python csv numpy matrix data-conversion

我有一个看起来像这样的矩阵:

    a   b   c   d
a   0   1   0   0
b   0   0   1   1
c   1   0   0   1
d   1   0   0   0

其中1表示行和列之间的单向关系。 例如:

a interacts with b
b interacts with c and d
c interacts with a and d
...

我需要的是一个包含三列的列表,它忽略了0并列出了交互。 例如:

a  1  b
b  1  c
b  1  d
c  1  a
...

目前我正在使用numpy并从csv文件中读取初始矩阵。

data = np.array(list(csv.reader(open("input.csv"))))

1 个答案:

答案 0 :(得分:1)

当我创建玩具数据矩阵a:

a = numpy.array([[0,1],[1,0]])
coords = ('a', 'b')
for i in range(len(coords)):
    for j in range(len(coords)):
        if a[i,j]:
            print coords[i], 1, coords[j]

输出:

a 1 b
b 1 a