2

I have a geopackage file, with a layer called "MyLayer". Within this I have an attribute table with approx 20 attributes.

I can read in each attribute individually like:

import geopandas as gpd

geopkg = gpd.read_file('MyGeoPkg.gpkg', layer='MyLayer')
A = geopkg['AttributeA']

However, I have multiple GPKG files and they may have a different number of attributes, that may have different names.

I'd like to automatically get a list like:

listOfAttributes = ['AttributeA', 'AttributeB', 'AttributeC']

so I could then do:

for l in listOfAttributes:
    data = geopkg[l]

Is there a way of getting a list of the field names from the layer so I can iterate over them?

1

You effectively want to iterate over columns of GeoDataFrame, which you can get using geopkg.columns.

So assuming you don't want to iterate over geometry field:

for col in geopkg.columns.drop('geometry'):
    data = geopkg[col]
  • Fiona.listlayers('MyGeoPkg.gpkg') returns the layer, which gives me 'MyLayer', it doesn't return me the attribute fields - unless I'm not using it as intended...? – Nathan Thomas Oct 9 at 13:48
  • 1
    Oh sorry, I got confused by your code. I will edit accordingly. – martinfleis Oct 9 at 15:52
  • my variable 'listOfLayers' was confusing. Will change to 'listOfAttributes'. Accepting as answer because it was the first and keeps it within geopandas/fiona – Nathan Thomas Oct 9 at 16:23
0

I found an answer here. There are several examples here, but this one works the best for my case:

source = ogr.Open('MyGeoPkg.gpkg')
layer = source.GetLayer()
schema = []
ldefn = layer.GetLayerDefn()
for n in range(ldefn.GetFieldCount()):
    fdefn = ldefn.GetFieldDefn(n)
    schema.append(fdefn.name)
print(schema)

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.