[GIS] Creating drop down of derived fields from CSV using ArcPy

arcpycsvparameterspython-script-tooltool-validation

I'm trying to create a drop down menu in a Python script in ArcMap where one input is a CSV and the other input is a drop down of the headers in that CSV. Is this possible at all?

enter image description here

In the image above, "Candidate List" is the supplied CSV and "Candidate Field" is the field header that the user selects for the column that the data is located in. Would I have to put something in the script its self or in the update parameters?

with open(Candidate List, "rb") as f:
    reader = csv.reader()
    i = reader.next()

Wherein I want I to be the fields for that drop down.

Best Answer

It is definitely possible. You would need to use script tool validation class.

  1. Read the .csv headers (can be done with csv or pandas, for instance).

With csv:

import csv
csv.DictReader(open(r"C:\GIS\grafiti.csv","r")).fieldnames
['FID', 'OBJECTID', 'CID', 'SqFtAprox', 'POINT_X', 'POINT_Y']

With pandas:

import pandas as pd
pd.read_csv(r"C:\GIS\grafiti.csv").columns.tolist()
['FID', 'OBJECTID', 'CID', 'SqFtAprox', 'POINT_X', 'POINT_Y']
  1. Use updateParameters to set values of the needed parameter to the list of columns.

Code:

self.params[2].filter.list = headers

Please look up the help page for more examples. Another helpful answer is here.

Related Question