2

I'm looking to populate a newly created field in a shapefile that from a list using basic python and osgeo tools. The values are integers and in a python list that is the length of the number of features in the shapefile. The goal is to have a set of unique numbers for grabbing random samples of features. Here is example.

from osgeo import ogr, osr
import os, sys
import random

driver = ogr.GetDriverByName ("ESRI Shapefile")
sampleshapefile = ogr.Open('shapefile.shp', 1)
sample = sampleshapefile.GetLayer()
new_field = ogr.FieldDefn('randnum', ogr.OFTInteger)
f40.CreateField(new_field)
ran = random.sample(range(1, len(sample)+1), len(sample))

I've seen the examples such as Programmatically populating shapefile field with polygon areas in OGR?. Yet in that example the for loop on each feature fills the field with the result of a geometry calculation on the feature. I'm looking to have the first value in the list "ran" be value in the "randnum" field of the first feature, second list value for the second feature and so on.

  • Loop over each feature in your layer using enumerate() to also return the index, which you can then use to retrieve the value from your list. You could also try itertools.izip() to loop over both at once without immediately exhausting the layer iterator. Examples of both approaches here. – mikewatt Feb 21 at 19:12
  • the zip function worked perfectly. Thanks for the recommendation. I learned two good things with one question! – jeremyg19 Feb 21 at 20:09
1

Possibly a lot easier with geopandas if that is available to use.

import geopandas as gp

file = gp.read_file('path/to/shapefile')
list = [stuff, stuff, stuff]
file['new_field_name'] = list
file.to_file('save/your/file')
  • Thank you for the recommendation. I had never used geopandas before but I think I will be more in the future now. – jeremyg19 Feb 21 at 19:52

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.