3

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?

GeoMonkey
  • 1,357
  • 11
  • 26

2 Answers2

2

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]
martinfleis
  • 2,407
  • 11
  • 17
  • 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...? – GeoMonkey Oct 09 '19 at 13:48
  • 1
    Oh sorry, I got confused by your code. I will edit accordingly. – martinfleis Oct 09 '19 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 – GeoMonkey Oct 09 '19 at 16:23
1

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)
GeoMonkey
  • 1,357
  • 11
  • 26