2

I have a shapefile from the Census Bureau on Zip Code Tabulation Areas (http://www.census.gov/cgi-bin/geo/shapefiles/index.php). I wanted to get, for each zip code, the list of neighboring zip codes.

More specifically, I would like to export a file that gives a dataset of the form,

ZIPCODE,NEIGHBOR1,NEIGHBOR2,NEIGHBOR3,NEIGHBOR4
90001,90002,90010,.,.
60640,60660,60625,60613,60618

So for each zip code, there would be columns which would be populated with neighboring zip codes. The column would be set to missing for zip codes that do not have as many neighbors.

Basically, I want to do this (Finding all neighbors for all polygons in Spatialite) in qgis. I guess I'm asking whether the command in the link would generate what I want described above, and if it does how I can run it. I have PostGIS installed at this point, but I do not know how I can load the vector on it using QGIS and PSQL...

Basically, I am very unfamiliar with QGIS, except being able to load a vector layer using .shp file. I would like to know how to get to the part where I can use the command like

SELECT p1.ROWID, p1.ZCTA5CE10, p2.ZCTA5CE10 
FROM "US_zcta5_2010" p1, "US_zcta5_2010" p2 
WHERE Touches (p1.Geometry, p2.Geometry)=1;
1

i'm sure there is a more clear way to do this and I don't know whether you want it as part of the shapefiles attributes or not, but in qgis, open a python terminal and execute the following code:

layer = iface.activeLayer()
itera = layer.getFeatures()
features=list(itera)
with open('/home/user/Desktop/neighbours.csv', 'wb') as out: #adjust accordingly
    for feature in features:
        neighbours=[]
        for pneighbours in features:
            if feature.geometry().touches(pneighbours.geometry()):
                neighbours.append(str(pneighbours.attributes()[0]))
            else:
                pass 
        out.write(str(feature.attributes()[0])+';'+';'.join(neighbours)+'\n')

The result will be something like:

1;2;3;5;6;8;9
2;1;3;4;8;9
3;1;2;4;5
4;2;3
5;1;3;6
6;1;5;8
8;1;2;6;9
9;1;2;8

The first number is the ID of the feature and the following numbers are the neighbouring IDs.

  • Thanks! That's working with the console command. However, I would like to export the data file (as a csv, or txt whatever that I can import to another program), instead of printing the result on the command console. How would I go ahead and do that? – user77220 Jul 3 '16 at 20:14
  • updated the answer. – vagvaf Jul 3 '16 at 23:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.