【问题标题】:pandas - reshape dataframe to edge list according to column valuespandas - 根据列值将数据框重塑为边缘列表
【发布时间】:2016-01-29 16:24:24
【问题描述】:

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

  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

我想构建一个 edgelist 文件以将其作为无向网络读取。预期的输出是:

b c
a d
a f
d f
e g

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

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

但后来我被困在按照我的意愿对用户进行分组。

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

【问题讨论】:

    标签: python pandas networkx


    【解决方案1】:

    看看这个:

    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')]

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-05
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多