简体   繁体   English

Networkx Multigraph from_pandas_dataframe

[英]Networkx Multigraph from_pandas_dataframe

Update: 更新:
The question, as written, is relevant to Networkx version < 2.0. 所写的问题与Networkx版本<2.0有关。 The from_pandas_dataframe method has been dropped . from_pandas_dataframe方法已删除
To accomplish the same task in Networkx >= 2.0, see the update to the accepted answer. 要在Networkx> = 2.0中完成相同的任务,请参见已接受答案的更新。

Trying to create a MultiGraph() instance from a pandas DataFrame using networkx's from_pandas_dataframe . 尝试使用networkx的from_pandas_dataframe从pandas DataFrame创建MultiGraph()实例。 What am I doing wrong in the example below? 在下面的示例中我在做什么错?

In [1]: import pandas as pd
        import networkx as nx

        df = pd.DataFrame([['geneA', 'geneB', 0.05, 'method1'],
                           ['geneA', 'geneC', 0.45, 'method1'],
                           ['geneA', 'geneD', 0.35, 'method1'],
                           ['geneA', 'geneB', 0.45, 'method2']], 
                           columns = ['gene1','gene2','conf','type'])

First try with the default nx.Graph(): 首先尝试使用默认的nx.Graph():

In [2]: G= nx.from_pandas_dataframe(df, 'gene1', 'gene2', edge_attr=['conf','type'], 
                                    create_using=nx.Graph())

As a non-MultiGraph(), I'm missing one of the duplicate edges: 作为非MultiGraph(),我缺少重复的边缘之一:

In [3]: G.edges(data=True)
Out[3]: [('geneA', 'geneB', {'conf': 0.45, 'type': 'method2'}),
         ('geneA', 'geneC', {'conf': 0.45, 'type': 'method1'}),
         ('geneA', 'geneD', {'conf': 0.35, 'type': 'method1'})]

With MultiGraph() : 使用MultiGraph()

In [4]: MG= nx.from_pandas_dataframe(df, 'gene1', 'gene2', edge_attr=['conf','type'], 
                             create_using=nx.MultiGraph())

This: 这个:

TypeError                                 Traceback (most recent call last)
<ipython-input-49-d2c7b8312ea7> in <module>()
----> 1 MG= nx.from_pandas_dataframe(df, 'gene1', 'gene2', ['conf','type'], create_using=nx.MultiGraph())

/usr/lib/python2.7/site-packages/networkx-1.10-py2.7.egg/networkx/convert_matrix.pyc in from_pandas_dataframe(df, source, target, edge_attr, create_using)
    209         # Iteration on values returns the rows as Numpy arrays
    210         for row in df.values:
--> 211             g.add_edge(row[src_i], row[tar_i], {i:row[j] for i, j in edge_i})
    212 
    213     # If no column names are given, then just return the edges.

/usr/lib/python2.7/site-packages/networkx-1.10-py2.7.egg/networkx/classes/multigraph.pyc in add_edge(self, u, v, key, attr_dict, **attr)
    340             datadict.update(attr_dict)
    341             keydict = self.edge_key_dict_factory()
--> 342             keydict[key] = datadict
    343             self.adj[u][v] = keydict
    344             self.adj[v][u] = keydict

TypeError: unhashable type: 'dict'

Question How do I instantiate a MultiGraph() from a pandas dataframe? 问题如何从熊猫数据帧实例化MultiGraph()

Networkx < 2.0: Networkx <2.0:
It's was a bug, I opened an issue on GitHub, once I made the suggested edit : 这是一个错误,完成建议的编辑后 ,我在GitHub上打开了一个问题:

It changed line 211 of convert_matrix.py to to read: 它将convert_matrix.py第211行更改为:

g.add_edge(row[src_i], row[tar_i], attr_dict={i:row[j] for i, j in edge_i})

Results from that change: (which have since been incorporated) 更改的结果:( 此后已合并)

MG= nx.from_pandas_dataframe(df, 'gene1', 'gene2', edge_attr=['conf','type'], 
                                 create_using=nx.MultiGraph())

MG.edges(data=True)
[('geneA', 'geneB', {'conf': 0.05, 'type': 'method1'}),
         ('geneA', 'geneB', {'conf': 0.45, 'type': 'method2'}),
         ('geneA', 'geneC', {'conf': 0.45, 'type': 'method1'}),
         ('geneA', 'geneD', {'conf': 0.35, 'type': 'method1'})]

Networkx >= 2.0: Networkx> = 2.0:
In DataFrames with this format (edge list), use from_pandas_edgelist 在具有这种格式的数据框(边缘列表)中,使用from_pandas_edgelist

MG= nx.from_pandas_edgelist(df, 'gene1', 'gene2', edge_attr=['conf','type'], 
                             create_using=nx.MultiGraph())

MG.edges(data=True)
MultiEdgeDataView([('geneA', 'geneB', {'conf': 0.05, 'type': 'method1'}),
                   ('geneA', 'geneB', {'conf': 0.45, 'type': 'method2'}),
                   ('geneA', 'geneC', {'conf': 0.45, 'type': 'method1'}), 
                   ('geneA', 'geneD', {'conf': 0.35, 'type': 'method1'})])

That's a nice question. 这是一个很好的问题。 I tried to reproduce your problem building your MultiGraph() in a different way, using only three/four columns with: 我尝试仅使用三列/四列,并以不同的方式重现您在构建MultiGraph()时遇到的问题:

MG = nx.MultiGraph()

MG.add_weighted_edges_from([tuple(d) for d in df[['gene1','gene2','conf']].values])

this correctly returns as MG.edges(data=True) : 这正确返回为MG.edges(data=True)

[('geneA', 'geneB', {'weight': 0.05}), ('geneA', 'geneB', {'weight': 0.45}), ('geneA', 'geneC', {'weight': 0.45}), ('geneA', 'geneD', {'weight': 0.35})]

I tried also with your from_pandas_dataframe method using only three columns but it doesn't work: 我也尝试了只使用三列的from_pandas_dataframe方法,但是它不起作用:

MG = nx.from_pandas_dataframe(df, 'gene1', 'gene2', edge_attr='conf', create_using=nx.MultiGraph())

this returns the same error you encountered. 这将返回您遇到的相同错误。 I don't know if it is a bug or that method doesn't support more than one weight type for MultiGraph() . 我不知道这是一个错误还是该方法不支持MultiGraph()多个权重类型。 In the meantime you can use the above workaround to build your MultiGraph, at least with only one weight type. 同时,您可以使用以上解决方法来构建MultiGraph,至少仅使用一种权重类型即可。 Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM