大熊猫-根据列值将数据框重塑为边缘列表


问题内容

从这个简单的数据帧开始:

  node   t1   t2
0    a  pos  neg
1    b  neg  neg
2    c  neg  neg
3    d  pos  neg
4    e  neg  pos
5    f  pos  neg
6    g  neg  pos

我想建立一个边缘列表文件以将其读取为无向网络。预期输出为:

b c
a d
a f
d f
e g

因此,基本上,如果两个节点在['t1','t2']列中具有相同的一对值,则我将它们链接在一起。到目前为止,我首先尝试将值分组到一个新列中:

d['c'] = [tuple(i) for i in df[['t1','t2']].values]

但随后,我就无法按需分组用户了。

编辑:修复新列创建中的错误。


问题答案:

看看这个:

df = pd.DataFrame({'node': ['a', 'b','c', 'd', 'e', 'f', 'g'],
               't1': ['pos', 'neg', 'neg', 'pos', 'neg', 'pos', 'neg'],
               't2': ['neg', 'neg', 'neg', 'neg', 'pos', 'neg', 'pos']})

K = nx.Graph()
K.add_nodes_from(df['node'].values)

# Create edges
for i, group in df.groupby(['t1', 't2'])['node']:
    # generate all combinations without replacement 
    # from the group of similar column pairs
    for u, v in itertools.combinations(group, 2):           
        K.add_edge(u, v)

print(K.edges())

结果:[(’a’,’d’),(’a’,’f’),(’c’,’b’),(’e’,’g’),(’d’,’f ‘)]

这里的技巧是在熊猫中同时将2列分组。然后,您可以只创建要添加到图中的所有边的组合。