I have this code that takes a matrix and creates an array of the adjacent neighbors of each element in the matrix. The elements are ids that I will use as a key to look up values in a dictionary. "Hooked" helped me tremendously with writing this code in numpy format. What I would like to do is export the neighbor list to a csv file. I'm having problems with the writer.writerows command in the code below. I get an error that a sequence is expected. I believe this is because it looking to write a list of lists where my output format does not have any commas between the list of neighbors.
The output from the code looks like:
[ 0. 0. 309. 0. 0. 10. 11. 12.]
[ 0. 309. 310. 0. 1. 11. 12. 13.]
[ 309. 310. 311. 0. 2. 12. 13. 14.]
[ 310. 311. 312. 1. 3. 13. 14. 15.]
[ 311. 312. 313. 2. 4. 14. 15. 16.]
[ 312. 313. 314. 3. 5. 15. 16. 17.]
[ 313. 314. 315. 4. 6. 16. 17. 18.]
[ 314. 315. 316. 5. 7. 17. 18. 19.]
[ 315. 316. 317. 6. 8. 18. 19. 20.]
[ 316. 317. 318. 7. 9. 19. 20. 21.]
Here's the code:
from numpy import *
import sys
import csv
k = 1
#Create nearest neighbors
Xidx, Yidx = mgrid[-k:k+1,-k:k+1]
#Remove the center (0,0) index
center = (Xidx==0) & (Yidx==0)
Xidx = Xidx[~center]
Yidx = Yidx[~center]
data = loadtxt("H:\SWAT\NC\GRID_FIDS2.txt")
#print data
for dx in range(11):
for dy in range(11):
FID = data[dx,dy]
#print FID
NL = data[Xidx+dx,Yidx+dy]
print NL
f = open("H:\SWAT\NC\Pro_NL.txt", 'wt')
try:
writer=csv.writer(f)
writer.writerows(NL)
finally:
f.close()
'''
dx,dy = 0,4
print "Cell Value data[%i,%i] = %f " % (dx, dy, data[dx,dy])
print "k=%i nearest neighbors: "%k, data[Xidx+dx, Yidx+dy]
'''
'
Ideally, what I would like is to have for the csv file is one column with all the FID values and the second column have the Neighbor List (NL) corresponding to the FID value. I appreciate any input on this...I've been testing different things all day without success!