お願いします。あなたのデータをcsvファイルに保存しました。ノード名の後に,
を追加し、空白をすべて削除しました。
Name1,2-s2.0-84905590088,2-s2.0-84901477890
Name2,2-s2.0-84941169876
Name3,2-s2.0-84958012773
Name4,2-s2.0-84960796474
Name5,2-s2.0-84945302996,2-s2.0-84953281823,2-s2.0-84944268402,2-s2.0-84949478621,2-s2.0-84947281259,2-s2.0-84947759580,2-s2.0-84945265895,2-s2.0-84945247800,2-s2.0-84946541351,2-s2.0-84946051072,2-s2.0-84942573284,2-s2.0-84942280140,2-s2.0-84937715425,2-s2.0-84943751990,2-s2.0-84957729558,2-s2.0-84938844501,2-s2.0-84934761065
Name6,2-s2.0-84908333808
Name7,2-s2.0-84925879816
Name8,2-s2.0-84940447040,2-s2.0-84949534001
Name9,2-s2.0-84899915556,2-s2.0-84922392381,2-s2.0-84905079505,2-s2.0-84940931972,2-s2.0-84893682063,2-s2.0-84954285577,2-s2.0-84934934228,2-s2.0-84926624187
Name10,2-s2.0-84907065810
一つの観察:あなたはName5
は、エッジがたくさんあるだろうが、その属性が一意であることを言います。さらに、データでコードを実行すると、すべての属性が一意であるため、グラフにエッジがありません。
私は各属性の最初の12文字(私はそれを行new_attributes = [x[:12] for x in new_attributes]
で行う)だけを使用するようにデータをtweekしました。そうすれば、いくつかの一致する属性が得られます。今
コード:各CSV行の
import networkx as nx
import csv
G = nx.Graph()
with open('data.csv') as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
for row in csv_reader:
new_node = row[0] # first element in row
new_attributes = row[1:] # whole row except the first element
new_attributes = [x[:12] for x in new_attributes] # remove this for your data!
# add the node and its attributes to the graph
G.add_node(new_node, my_attributes=new_attributes) # attributes are stored as a list
# add edges based on existing nodes
for node, attrs in G.nodes(data=True):
# skip node we just added
if node != new_node:
for attr in attrs['my_attributes']:
# check if any of the attributes for `node` are also in the `new_attributes` list
if attr in new_attributes:
G.add_edge(node, new_node)
for edge in G.edges():
print('EDGE:', edge, '| COMMON ATTRIBUTES:', set(G.node[edge[0]]['my_attributes']) & set(G.node[edge[1]]['my_attributes']))
Iグラフに(その属性を持つ)ノードを追加し、現在のグラフのノード(およびその属性)に基づいて、Iは、エッジを追加します。 ノードの属性はリストに格納されており、my_attributes
キーでアクセスできます。 最後に、特定のエッジのノードの一致する属性でエッジを印刷します(私はset
と&
を使用して2つの属性リストの共通部分を取得します)。 tweekedデータの
出力:
EDGE: ('Name5', 'Name9') | COMMON ATTRIBUTES: {'2-s2.0-84934'}
EDGE: ('Name5', 'Name8') | COMMON ATTRIBUTES: {'2-s2.0-84949'}
EDGE: ('Name8', 'Name9') | COMMON ATTRIBUTES: {'2-s2.0-84940'}
EDGE: ('Name1', 'Name9') | COMMON ATTRIBUTES: {'2-s2.0-84905'}
最後の注意:あなたは2つのノード間の複数のエッジを持っている必要がある場合はMultiGraph
を使用しています。
NetworkXで組み込みの方法はありませんが、すべてのノードを作成してから、「属性」を繰り返して適切なエッジを追加することで、確かにそれを実行できます。 – BrenBarn