网络 X From_Pandas_dataframe

NetworkX From_Pandas_dataframe

NetworkX 出现错误,显示 'module' 没有属性 'from_pandas_dataframe.'

我有一个名为 nflroster 的数据框,其格式为:

Index   . . . Player           Team       Year

0       . . . Player1          Team1      2014

1       .  . .Player2          Team1      2014


2       . . . Player3          Team2      2014
.
.       . . .   .                .         .

所以根据这里的文档 networkx documentation 下面这行应该可以工作

G = nx.from_pandas_dataframe(nflroster,str, 'Team')

然而当我运行 this in Ipy notebook I 运行进入错误,'module' object has no attribute 'from_pandas_dataframe'.

我导入以下内容

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
from pandas import DataFrame as df

我在这里遇到了同样的问题。我是这样解决的:

尝试从源代码安装 networkx,而不是通过 pip 安装。

逐步安装源代码

    Download the source (tar.gz or zip file) from https://pypi.python.org/pypi/networkx/ or get the latest development version from https://github.com/networkx/networkx/
    Unpack and change directory to the source directory (it should have the files README.txt and setup.py).
    Run python setup.py install to build and install

请注意,此特定函数 From_Pandas_dataframe 将安装在 networkx 文件夹的 convert_matrix.py 文件中。

您可能安装了不正确的 networkx 版本。你可能应该检查你是否有 1.10.0 <= see history here

如果我们查看 networkx 的构建文件夹,在 __init__.py 中,我们会看到来自 networkx.convert_matrix 的导入。通过 convert_matrix.py 文件,我们可以看到以下允许的外部依赖项:

__all__ = ['from_numpy_matrix', 'to_numpy_matrix',
           'from_pandas_adjacency', 'to_pandas_adjacency',
           'from_pandas_edgelist', 'to_pandas_edgelist',
           'to_numpy_recarray',
           'from_scipy_sparse_matrix', 'to_scipy_sparse_matrix',
           'from_numpy_array', 'to_numpy_array']

如您所见,from_pandas_dataframe 不存在。尽管这可能已经在 1.10 version 中了。

所以最后还是要时刻注意版本号。

另一种在 Networkx 中搜索方法的方法 API:

In [199]: [m for m in nx.__dir__() if 'pandas' in m]
Out[199]:
['from_pandas_adjacency',
 'to_pandas_adjacency',
 'from_pandas_edgelist',
 'to_pandas_edgelist']