0

I have an edge list and am trying to predict links using the adamic_adar_index in networkx. The documentation says it returns an iterator object. I want to save the results to a csv file but can't figure out how to "unpack" the rows.

The edge list looks like this:

Bob Smith, Ted Jones

Carol Thompson, Alice Johnson

This is what I've tried:

import csv
import networkx as nx

G = nx.read_edgelist("fakeedge3.txt", delimiter=",", create_using=nx.Graph(), nodetype=str)
pred = nx.adamic_adar_index(G)

#If I print, I get exactly what I want
print(sorted(pred, key=lambda pred: pred[2], reverse=True))

#But if I try to write to CSV I get a blank spreadsheet

with open ("testpred.csv", "w") as f:
predWriter = csv.writer(f)
for row in pred:
    predWriter.writerow(row)

I realize this has something to do with the iterator object, but I'm missing why I can't iterate through it with csv.writer the same way I do with the print function.

Bryan Lee
  • 25
  • 1
  • 6
  • You've got a comment saying if you print it you get exactly what you want. What happens if you don't print it first - does it then output correctly? – Joel Jun 16 '17 at 22:13
  • Thanks for the pointer to the other question. What you are saying is the print call basically destroys the iterator, which is a one-time deal, so if I want to use it to write a csv I have to call it again. I did that, and it worked. – Bryan Lee Jun 16 '17 at 22:17
  • Thanks too to @Joel for trying to lead me gently in the same direction. – Bryan Lee Jun 16 '17 at 22:18

0 Answers0