[GIS] quick way to clear all attributes from a layer but leave the polygons in place

attribute-tableqgisqgis-2.6

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.

Best Answer

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.


UPDATE:

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()
Related Question