问题
I am trying to represent relationships between numbers in column A and their corresponding values in B.
A B
Home [Kitchen, Home, Towel]
Donald [US, 02 , Donald, Trump]
Trump [Trump,Family, Cat, Dog]
Dog [Dog,Cat,Paws]
Numbers in column A and numbers in B are nodes in a graph. I would like to connect elements in B to A or to each other. For example:
- Home in A is linked with itself; if I look within B column (the value appears only in the first row), Home in B is connected to Kitchen and Towel (ingoing link);
- Donald is linked with itself in as Donald is only in B; however, Donald in B is connected also with US, 02 and Trump (ingoing link);
- Trump has an outgoing link with Donald and ingoing links (Family, Cat and Dog);
- Dog has an outgoing link with Trump and ingoing links (Cat and Paws).
The rule should be the following then:
- if a word in A is in another row in B, then create an outgoing link;
- for each word in B create an ingoing link to the word in A, if the word in A is also included in B.
How should I adjust my code?
file = file.assign(B=file.B.map(list)).explode('B')
G = nx.DiGraph()
nx.add_path(G, file['A'])
nx.add_path(G, file['B'])
nx.draw_networkx(G)
plt.show()
回答1:
Converting your table to a pandas dataframe
and then looping through its rows you can add the corresponding edges like this:
import networkx as nx
import pandas as pd
from pyvis.network import Network
df = pd.DataFrame(
[
['Home', ['Kitchen', 'Home', 'Towel']],
['Donald', ['US', '02' , 'Donald', 'Trump']],
['Trump', ['Trump','Family', 'Cat', 'Dog']],
['Dog', ['Dog', 'Cat' , 'Paws']]
],
columns=['A', 'B']
)
G = nx.DiGraph()
for i, j in enumerate(df['A']):
for index, row in df.iterrows():
if i != index:
if j in row['B']:
G.add_edge(row['A'], j)
else:
for n in row['B']:
if j != n:
G.add_edge(j, n)
if G.in_degree(j) == 0:
G.add_edge(j , j)
N = Network(directed=True) # using pyvis to show self loops as well
for n, attrs in G.nodes.data():
N.add_node(n)
for e in G.edges.data():
N.add_edge(e[0], e[1])
N.write_html('graph.html')
Which gave me the following graph:
Hope this is what you wanted!
来源:https://stackoverflow.com/questions/63441510/building-terms-relations-within-a-network