2024-10-01 07:42:00 发布
网友
我有以下pandas dataframe包含一个edgelist,如下所示:
name1 name2 weight 0 $hort, Too Alexander, Khandi 0.083333 1 $hort, Too B-Real 0.083333
我想从pandas数据帧(而不是从文件)创建一个igraph对象。 这张图太大了,所以我不能把它转换成邻接矩阵。怎么做?在
我总是这样做,虽然我经常重复边,这就是为什么我的权重容易改变(我假设你的熊猫数据帧命名为df):
import igraph edgelist = [] weights = [] for i in df.index(): edge = (df.ix[i, 'name1'], df.ix[i, 'name2']) if edge not in edgelist: edgelist.append(edge) weights.append(1) else: weights[edgelist.index(edge)] += 1 G = Graph() G.add_edges(edgelist) G.es['weight'] = weights
我也在寻找Networkx,它与igraph中的函数等价,我发现图.TupleList()是最佳解决方案。 所以基本上你从3个pandas列创建一个tuple,然后使用这个函数来创建网络。在
tuples = [tuple(x) for x in df.values] Gm = igraph.Graph.TupleList(tuples, directed = True, edge_attrs = ['weight'])
igraph需要元组,pandas提供.itertuples(),用于一对:
(source, target, weight(optional))
假设您的数据帧名为“df”,您可以通过以下方式从pandas数据帧中获取具有权重的有向图对象:
根据https://igraph.org/python/doc/igraph.Graph-class.html#TupleList
weights - alternative way to specify that the graph is weighted. If you set weights to true and edge_attrs is not given, it will be assumed that edge_attrs is ["weight"] and igraph will parse the third element from each item into an edge weight
所以在您的例子中,您不需要“edge_attrs=”,但我添加了它,以备更一般的解决方案。在
我总是这样做,虽然我经常重复边,这就是为什么我的权重容易改变(我假设你的熊猫数据帧命名为df):
我也在寻找Networkx,它与igraph中的函数等价,我发现图.TupleList()是最佳解决方案。 所以基本上你从3个pandas列创建一个tuple,然后使用这个函数来创建网络。在
igraph需要元组,pandas提供.itertuples(),用于一对:
假设您的数据帧名为“df”,您可以通过以下方式从pandas数据帧中获取具有权重的有向图对象:
^{pr2}$根据https://igraph.org/python/doc/igraph.Graph-class.html#TupleList
所以在您的例子中,您不需要“edge_attrs=”,但我添加了它,以备更一般的解决方案。在
相关问题 更多 >
编程相关推荐