PyQGIS Attribute Fields – How to Write Attribute Column Names Based on Their Value

pyqgispythonqgisqgis-plugins

I have a tricky question: for a QGIS script, I need to filter a list of attribute column names (fields) of a vector based on the attribute value of each column.

My Vector is structured like this:

Attributtable

I create the list of field names with:

layer = QgsVectorLayer(Input_Layer, "ogr")
fields = layer.pendingFields()
field_names = [field.name() for field in fields]

So field_names gives me a list of all the attribute field names:

[u'NAME_A', u'NAME_B', u'NAME_C']

I now need to filer the list, so attribute fields are only listed in field_names if the attribute value (there is only one attribute) is not NULL. So the result should only list:

[u'NAME_A', u'NAME_C']

I can't figure it out. Running QGIS 2.18.18 on Windows 10

Best Answer

This will solve your problem:

fields = layer.pendingFields()
field_names = [field.name() for field in fields]

temp = list(field_names)
for field in temp:
    index  = layer.fieldNameIndex(field)
    values = layer.uniqueValues(index)

    # if "any" record has null field value, remove that field
    if None in values:
        field_names.remove(field)

    # If "all" records have null value, then remove that field
    # if None in values and len(values)==1:
        # field_names.remove(field)

Sample table: (Empty cells have null value)

enter image description here

print(field_names)
# OUT: [u'c']

But note that: If type of any field is string and you delete field value (you get empty field), It won't be null, just empty string.

Related Question