1

I have a shapefile loaded into QGIS.When i apply filter i can quickly see all the unique values in that column. Is there a quick way to extract that for use in code? I know i could load the shapefile into a geo database and extract from there but for a single file that seems a lot of setup

mapping dom
  • 1,492
  • 1
  • 11
  • 24

2 Answers2

2

Vector layers have a uniqueValues function, which is available from Python:

v = iface.activeLayer()
idx = v.fieldNameIndex('your_column_name')
vals = v.uniqueValues(idx)

You can try it in the Python console to get the unique values from column 'your_column_name' of the active layer. The vals list contains all unique values (unsorted).

Zoltan
  • 7,325
  • 17
  • 27
  • This worked for me perfectly. I had to adapt the idx-line though. v = iface.activeLayer() idx = v.fields().indexFromName('your_column_name') vals = v.uniqueValues(idx) – Motti Jan 11 '22 at 20:19
0

There's lots of possible approaches you could use and here's three:

Quick (and nasty but effective): Open the dbf portion of the shapefile in Excel (or OpenOffice/Libre Office etc) and pull the unique values out and save as a CSV or something. See here for details. It is not recommended to fiddle with the separate parts of of shapefile, but if you know what you're doing and/or make a copy of the dbf file first - you shouldn't come to any harm.

Slightly less Quick (and much less nasty): read the dbf in read-only mode from within the program that is going to use the values. How you do this will depend entirely on the programming language you decide to use, so I can't go into details here, but GDAL libraries (available for Python, Java and C++) will help.

Another option (no quicker than your own suggestion but less setup): Load your shapefile into SpatialLite and use the db functions to pull out the unique vales.

MappaGnosis
  • 33,857
  • 2
  • 66
  • 129