如何从给定的 csv 文件创建图表?

How to create a graph from a given csv file?

我试图从社交网络的 csv 文件创建图表。 csv 文件有 2 行:Friend1、Friend2。

这里是我的文件 graph.ipynb:

import networkx as nx
import numpy as np
import pandas as pd
%matplotlib notebook
%matplotlib inline

df = pd.read_csv('file1.csv')
Graphtype = nx.Graph()
G = nx.from_pandas_edgelist(df,  create_using=Graphtype)

nx.draw(G)
plt.show()

在 jupyter 上 运行 后报错:

KeyError: 'source'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-5-5d8670ba64af> in <module>
      7 df = pd.read_csv('file1.csv')
      8 Graphtype = nx.Graph()
----> 9 G = nx.from_pandas_edgelist(df,  create_using=Graphtype)
     10 
     11 nx.draw(G)

我无法解决这个错误。

当您调用 nx.from_pandas_edgelist() 时,您需要指定 sourcetarget 参数以及有效的列名。 (除非您有名为 'source''target' 的列,在这种情况下,它们将被选为自动默认值)。参见 docs

由于我们不知道您的 .csv 文件是什么样的,我冒昧地创建了一个示例 df 来进行演示。

像这样:

import networkx as nx
import numpy as np
import pandas as pd
%matplotlib notebook
%matplotlib inline

# df = pd.read_csv('file1.csv')
df = pd.DataFrame({'friends':'jack', 'enemies':'jill'}, index=[1])

Graphtype = nx.Graph()
G = nx.from_pandas_edgelist(df, 'friends', 'enemies',  create_using=Graphtype)

nx.draw(G)
plt.show()

我现在注意到你说 我正在尝试从 csv 文件为社交网络创建图表。 csv 文件有 2 行:Friend1、Friend2。

如果 'Friend1' 和 'Friend2' 是行,那么你需要转置你的数据框,使它们成为列:

df2 = df.transpose()

然后您应该能够将这些列设置为源和目标:

G = nx.from_pandas_edgelist(df, 'Friend1', 'Friend2',  create_using=Graphtype)