1

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.

3

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
  • 1
    It saved lots of hassle. Previously I have been using extra 10 lines of codes where it can do the same job with only two lines. – Sourav Sep 18 '18 at 23:12

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.