3

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

2

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.

  • Great, I tryed the code and it worked so far as expected! Thanks a lot – Miron Apr 25 '18 at 14:52
  • Hm, there must be a slide mistake in the code. The result is right, all the fields that are != NULL remain in the list, but there are always also fields in the list that have NULL field values. It must have something todo with the index that changes after removing the filed in the for loop… – Miron Apr 27 '18 at 9:46
  • You're 'right. I editted the answer. – Kadir Şahbaz Apr 27 '18 at 11:55

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.