For 循环嵌套:如何遍历两列?

问题描述

我需要在两个不同列中的值之间迭代一个过程:

     A                      B                   score      Value    
0   user1               test1                    6.6        A
1   user1               test2                    3.2        AA
2   user241             test1                    4.8        B
3   user12              test4                    3.1        C
4   user1               test1a                   2.9        A

具体来说,我需要链接

- user1 with test1,test2 and test1a
- user241 with test1
- user 12 with test4
...

为了创建网络。 我尝试如下

from pymnet import *
import matplotlib.pyplot as plt

mnet = MultilayerNetwork(aspects=1)
for i in df['A']:
    for j in df['B']:
        mnet[i,j,'friendship','friendship'] = 1

fig=draw(mnet,show=True,figsize=(25,30))

但它似乎没有按预期链接 A 和 B。 问题出在 for 条件中。

你能帮我弄清楚如何正确运行 for 循环吗?

解决方法

通过这个双循环,您可以在每个 A 和每个 B 之间建立连接。

enter image description here

您可以按照以下操作

for index in df.index:
    mnet[df.loc[index,'A'],df.loc[index,'B'],'friendship','friendship'] = 1

for A,B in zip(df['A'],df['B']):
    mnet[A,B,'friendship'] = 1