How to add data to a feature class from pandas DataFrame using InsertCursor class?

2074
1
11-01-2019 08:08 AM
ImtiazSyed
New Contributor III
0 1 2,074

I created the below script to help pipeline data from a csv file which consists of list of attributes of a county to pandas DataFrame and then to a feature class located in a SQL Server database. The cvs file consists of columns names which match with some of the field names in the feature class to help map the columns to the fields while loading the data.

 

The class I used is: InsertCursor. Before the input rows are given to the InsertCursor method, it is converted to a list using the values.list() method as InsertCursor expects a list or a tuple if its not for a single field. In the below script I am adding a subset of 100 rows and 3 columns, but you can insert and entire single column without actually having to convert it to a list. For eg: df['column-name'] where the column-name refers to one of the columns of the DataFrame can be inserted to the matching field in the feature class with all the column features. 

 

The other ways of adding/ updating data is using UpdateCursor and/ or using combination of SearchCursor with either Update or Insert.

import arcgis
import pandas as pd
import arcpy
from arcpy import env
import os

#Import the csv to pandas dataframe
pd.set_option('display.max_columns', None)  
df = pd.read_csv(r'<File_Name>.csv', dtype=str, sep='|', encoding = "ISO-8859-1")
df.head(20)

#Subset of DataFrame consisting of 3 columns and 100 rows each
inputs = df.loc[0:100,['column1','column2', 'column3']].values.tolist()

fields = ['field1','field2','field3']

env.overwriteOutput = True

env.workspace = r"X:\<sde location>"
fcname = "Feature Class"
fc = os.path.join(env.workspace,fcname)

try:
    InsertCursor = arcpy.da.InsertCursor(fc,fields)
    for row in inputs:
        InsertCursor.insertRow(row)
except TypeError as e:
    print(f'A TypeError has occurred: {e}')‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
1 Comment
About the Author
GIS Developer
Labels