I wrote a function that should read in multiple feature classes and return pandas dataframes. Here is the code:
import pandas as pd
from arcgis.features import GeoAccessor, GeoSeriesAccessor
CHList=arcpy.ListFeatureClasses('*CH') # list feature classes from ArcGIS Pro and assign to variable
def DF_from_Ftr(in_features):
for feature in in_features:
sdf = pd.DataFrame.spatial.from_featureclass(feature) #use geoaccessor to convert ftr to df
sdf.drop(['SHAPE'], axis=1, inplace=True)
return sdf
When I run the function as follows:
DF_from_Ftr(CHList)
One dataframe is shown in the print screen.
When i try to access the other dataframes (there should be 30 of them) using indexing (shown in code below), I get a key error for whatever index number I use indicating that dataframe object isn't there.
DF_from_Ftr(CHList)[1]
What might I be doing wrong here?
Thank you!
Solved! Go to Solution.
Your function is returning one sdf. The last one from the input. Create an empty list in the function and append in each sdf, then return the list, as below.
def DF_from_Ftr(in_features):
sdf_list = []
for feature in in_features:
sdf = pd.DataFrame.spatial.from_featureclass(feature) #use geoaccessor to convert ftr to df
sdf.drop(['SHAPE'], axis=1, inplace=True)
sdf_list.append(sdf)
return sdf_list
Call your function
sdf_list = DF_from_Ftr(CHList)
Then access the elements of the list with indexing
sdf_1 = sdf_list[0]
sdf_2 = sdf_list[1]
sdf_3 = sdf_list[2]
## and so on
If CHList is a list, then you need to index it inside your function:
DF_from_Ftr(CHList[1])
Thanks for your response-- reading that I would think that would perform the function on the second item in CHList--but the output is an OSError: "C" does not exist.
Your function is returning one sdf. The last one from the input. Create an empty list in the function and append in each sdf, then return the list, as below.
def DF_from_Ftr(in_features):
sdf_list = []
for feature in in_features:
sdf = pd.DataFrame.spatial.from_featureclass(feature) #use geoaccessor to convert ftr to df
sdf.drop(['SHAPE'], axis=1, inplace=True)
sdf_list.append(sdf)
return sdf_list
Call your function
sdf_list = DF_from_Ftr(CHList)
Then access the elements of the list with indexing
sdf_1 = sdf_list[0]
sdf_2 = sdf_list[1]
sdf_3 = sdf_list[2]
## and so on
Ah, yes! Many thanks!