return and access multiple dataframes from a function

Viewed 36

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!

1 Answers

Because you repetitive assign sdf variable so you just get one df after run that function.

Consider this change and make a dictionary of df

def DF_from_Ftr(in_features):
    dict_features_df = {}
    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)
        dict_features_df[feature] = sdf
    return dict_features_df

then we can access feature in CHList by feature name.

df mean pd.DataFrame object.

Related