TransWikia.com

Finding the index of a field with its name using arcpy

Geographic Information Systems Asked by msc87 on July 28, 2021

I want to extract the index of a field with its name using arcpy. It seems what I have written is so dumb. Is there any simpler method with out using for-loop?

    import arcpy

    fieldList = arcpy.ListFields(self.address_ref_layer1)
    self.field_name = []
    for field in fieldList:
        self.field_name.append(field.name)
    #self.remove_pseudo_nodes()
    print self.field_name
    print self.field_name.index(u"NAMN1")

It could also be written:

    fieldList = arcpy.ListFields(self.address_ref_layer1
    name_index = [f.name for f in fieldList].index(u"NAMN1")

The ListFiled function returns list of field objects with many properties as well as name, but no function to return the index of the field which has a specific name?

5 Answers

You might want to investigate the FieldMappings object, which has various methods which deal with indices.

Instead of using for loops, you can use list comprehensions, like so:

self.field_name = [field.name for field in fieldList]

It can be shortened even further, since you may not need to store fieldList at all:

self.field_name = [field.name for field in arcpy.ListFields(self.address_ref_layer1)]

Answered by Paul on July 28, 2021

This Python function will return the Index Name associated with the FeatureClass and Field Name passed in.

def getIndexName(fieldname,fc):
    indexes = arcpy.ListIndexes(fc)
    for index in indexes:
        for f in index.fields:
            if f.name.upper() == fieldname.upper():
                return index.name

Answered by klewis on July 28, 2021

I struggled to find an answer for this on the ESRI sites which is why I ended up here. The clue is the object has field.

import arcpy
from arcpy import env
FC = r'Your_FC'
indexes = arcpy.ListIndexes(FC)
    for index in indexes:
        for fieldname in index.fields:
        fieldname = fieldname.name
        indexname = index.name
        print fieldname, indexname

Answered by Mark on July 28, 2021

You can also create a function that will return the index of a field:

import arcpy
def findindex(table,fieldname):
    return [i.name for i in arcpy.ListFields(table)].index(fieldname)

Input a feature class or table and the field name:

>>>findindex(r'C:GISTest.shp','EKOSTAT')
8

Answered by BERA on July 28, 2021

Here's how to get the field index number with FieldMapping:

def get_field_index(table, fieldName):
    # Return: the index number of the fieldName in the table.
    field_map = arcpy.FieldMappings()
    field_map.addTable(table)
    field_index = field_map.findFieldMapIndex(fieldName)
    return field_index

Answered by blueinc spatial on July 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP