[GIS] Set visible/ratio for make feature layer based on a list

arcgis-desktoparcpy

So, I have a feature class with three integer fields. I need to create a feature layer based on this feature class to use it later for running some GP tools where the values of the integer fields will be used for some calculations (with ratio).

fieldA fieldB fieldC
  25     60     70

However, I don't know what field should be used, this is something that I read from a look-up table. So, when I have read the look-up table, I get a list that looks like:

 [fieldA,fieldB]

Great, now I know which fields I want to use ratio for, i.e., which one will be taken into analysis. However, I am not sure how I should approach this, that is, how can I specify in the fieldinfo variable what field should have VISIBLE RATIO based on the input list with their names. The whole fieldinfo variable is just a string and I can't see any smart way of "getting VISIBLE RATIO right after the fieldA and the fieldB" (as in the example scenario).

fieldinfo = "fieldA fieldA VISIBLE RATIO; \
             fieldB fieldB VISIBLE RATIO; \
             fieldC fieldC HIDDEN NONE"

arcpy.MakeFeatureLayer_management(input_fc,inputfeaturelayer,"#","#",fieldinfo)

I looked at the fieldinfo arcpy class, but not really sure if this will help me here and if yes how I should use it.

EDIT: before using the field_info I was forced to use the str.replace() to update the fieldinfo object.

for field in fields_list: 
        updated_makefeaturelayer_fieldmapping = updated_makefeaturelayer_fieldmapping.replace('{0} {0} HIDDEN NONE'.format(field),'{0} {0} VISIBLE RATIO'.format(field))

Best Answer

This isn't the most elegant solution, but I have recently used something similar to hide 40+ fields that weren't needed. I don't know how you get the names/index of fields that you need. This example just has a list of names.

import arcpy
arcpy.env.workspace = "in_memory"
feature_class = "\\...\\feature_class"

keep_list = ["fieldA", "fieldB"]

arcpy.MakeFeatureLayer_management(feature_class, "layer")
desc = arcpy.Describe("layer")
field_info = desc.fieldInfo

field_list = []
for field in arcpy.ListFields("layer"):
    field_list.append(field.name)
for x in range(0, len(field_list)):
    if field_list[x] not in keep_list:
        field_info.setVisible(x, "HIDDEN")
    else:
        field_info.setSplitRule(x, "RATIO")

# run analysis or
# arcpy.Copy_management("layer", some_output);
# the output will only have the visible fields, (keep_list)
Related Question