Use feature layer alias for column names in dataframe

144
2
Jump to solution
05-13-2021 12:39 AM
Evman
by
New Contributor II

Hi, 

I am  converting a featurelayer to pandas dataframe in ArcGIS online notebooks, but I want the column names come from the layer's field aliases not the field names.  Using DataFrame.spatial.from_layer() has no option for this.  Does anyone know another way this can be achieved?

thanks

 

0 Kudos
1 Solution

Accepted Solutions
jcarlson
MVP Regular Contributor

Late answer, but yes! Totally possible, though requiring a couple of extra steps.

We'll use pandas' rename method on the dataframe, which takes the columns parameter of a dict in the format

{
'old_column_name':'new_column_name',
'another_old':'another_new'
...
}

First, we need to construct that dict. The featurelayer object should have a properties property which returns the JSON definition. Within that definitions is the fields list. Each item in the list is its own dict with values for "name" and "alias". We'll iterate over this and populate values in an empty dict, rep_dict, then use that in the rename method.

 

from arcgis import GIS
from arcgis import GeoAccessor

# get layer, convert to dataframe
fl = gis.content.get('your_layer_itemid').layers[0]
sdf = GeoAccessor.from_layer(fl)

# construct rep_dict
rep_dict = {}

for f in fl.properties['fields']:
    rep_dict[f['name']] = f['alias']

# rename fields
sdf.rename(columns=rep_dict, inplace=True)

 

 

And that should do it!

- Josh Carlson
Kendall County GIS

View solution in original post

0 Kudos
2 Replies
jcarlson
MVP Regular Contributor

Late answer, but yes! Totally possible, though requiring a couple of extra steps.

We'll use pandas' rename method on the dataframe, which takes the columns parameter of a dict in the format

{
'old_column_name':'new_column_name',
'another_old':'another_new'
...
}

First, we need to construct that dict. The featurelayer object should have a properties property which returns the JSON definition. Within that definitions is the fields list. Each item in the list is its own dict with values for "name" and "alias". We'll iterate over this and populate values in an empty dict, rep_dict, then use that in the rename method.

 

from arcgis import GIS
from arcgis import GeoAccessor

# get layer, convert to dataframe
fl = gis.content.get('your_layer_itemid').layers[0]
sdf = GeoAccessor.from_layer(fl)

# construct rep_dict
rep_dict = {}

for f in fl.properties['fields']:
    rep_dict[f['name']] = f['alias']

# rename fields
sdf.rename(columns=rep_dict, inplace=True)

 

 

And that should do it!

- Josh Carlson
Kendall County GIS

View solution in original post

0 Kudos
Evman
by
New Contributor II

Worked perfect! Thank you

0 Kudos