I have a Shapefile layer in QGIS 2.6 with several polygons, each of which has data in over 100 fields. I need to create a new layer with all the same polygons, but with all their data fields blank (set to 0, Null or empty depending on the field type). Is there a quicker way of doing this than pressing delete on each field of each polygon one at a time, I would have to do this more than 1000 times this way.
Can't you just copy-and-paste your data into Layer X (a layer/shapefile/feature class/whatever) that has no attributes (besides OID and Geometry) and then copy-and-paste the now "empty" geometry back into your original layer?
You can enter the following code in the Python Console to clear ALL attributes to
NULL for a shapefile loaded into QGIS. Select the layer from the layers panel (Table of Contents) and run the code:
layer = qgis.utils.iface.activeLayer() layer.startEditing() for field in layer.dataProvider().attributeIndexes(): for feature in layer.getFeatures(): layer.changeAttributeValue(feature.id(), field, NULL) layer.commitChanges()
This was tested on QGIS 2.8.2.
In response to the comment by @Vince, the following code can be directly copied/pasted into the Python console and will change the values of attributes depending on the type of field (i.e.
0 for integer fields;
NULL for string fields; and an epoch of
1900-01-01 for a Date field):
layer = qgis.utils.iface.activeLayer() layer.startEditing() for field in layer.pendingFields(): if field.typeName() == 'Integer': name_int = field.name() for feature in layer.getFeatures(): feature[name_int] = '0' layer.updateFeature(feature) if field.typeName() == 'String': name_str = field.name() for feature in layer.getFeatures(): feature[name_str] = NULL layer.updateFeature(feature) if field.typeName() == 'Date': name_dat = field.name() for feature in layer.getFeatures(): feature[name_dat] = '1900-01-01' layer.updateFeature(feature) layer.commitChanges()
You can simply save it as a new file and tick the "Skip Attribute Creation" box in the "Save as..." dialog. It does exactly what it says.
There will be one numeric counter column named FID, apparently the Shapefile format requires at least one attribute? If you can, use something better, spatialite or geopackage.
Open the .dbf file with openoffice or others, and remove the data.
You can use python to loop over the files and remove all but the headers See dbf python module
QGIS can open shape files without the .dbf.
So you could just delete the .dbf component and load in the .shp, which will bring in just the geometry.
Perhaps you can edit the *.dbf file with Excel.
Then you delete all fields but the geom one.
Finally save and quit.
It would be useful to keep an archive of the *.shp before doing this.
In QGIS 2.8.x you can also get rid of specific or all fields. Open attribute table, Toggle editing mode, Click on "Delete column" button, Select all your unwanted attributes and Click "OK". Save edits.