ArcGIS CSV Management – Appending List to Column of a CSV File Using ArcPy

arcgis-proarcmaparcpycsvspatial-analyst

There are 5 polygons in a shapefile. I am extracting the mean value of the NDVI pixel inside each polygon using "zonal statics as table". At this moment, I have 3 NDVI files, thus, I will get 3 sets of values. The codes are as follow

NDVI = ['1.tif', '2.tif', '3.tif']
poly_shape  = "polygon.shp"
table = r"E:\dump.gdb\NDVI_table.dbf"


for NDVI_file in NDVI:
    arcpy.gp.ZonalStatisticsAsTable_sa(poly_shape, "FID", NDVI_file, table, "DATA", "MEAN")
    single_list = [i[0] for i in arcpy.da.SearchCursor(table, "MEAN")]

As you can see, in each pass of the for loop I am getting one new list. I would like to create a CSV file to store the values. After each pass, I want to assign the values of the list in a new column.

To make it clear, after 1st pass, I will get the list below

single_list = [1,2,3,4,5]

after 2nd pass

single_list = [6,7,8,9,10]

after 3rd pass

single_list = [11,12,13,14,15]

I want the csv file to look like the following table (the first row will act as header and contain the raster file name)

1.tif   2.tif   3.tif
1       6       11
2       7       12
3       8       13
4       9       14
5       10      15

Is there any way to do that? I am using both ArcMap 10.6 and ArcGIS Pro 2.

Best Answer

You can use pandas module which is included in 10.6 and Pro:

pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language.

import arcpy
import pandas as pd

NDVI = ['1.tif', '2.tif', '3.tif']
poly_shape  = "polygon.shp"
table = r"E:\dump.gdb\NDVI_table.dbf"

df = pd.DataFrame() #Create empty data frame

for NDVI_file in NDVI:
    arcpy.gp.ZonalStatisticsAsTable_sa(poly_shape, "FID", NDVI_file, table, "DATA", "MEAN")
    single_list = [i[0] for i in arcpy.da.SearchCursor(table, "MEAN")]
    df[NDVI_file] = pd.Series(single_list) #Add new column named after file and fill with values from list

df.to_csv(r'C:\folder\csvfile.csv', index=False) #Save as csv