Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a QgsVectorLayer into a pandas dataframe?

How can you convert a QgsVectorLayer object into a pandas dataframe to store into a variable in python?

My process starts with the calculation of the zonal statistics for a raster file using the following line of code:

result = processing.run("native:zonalstatisticsfb", {'INPUT': shapefile,
                                                'INPUT_RASTER': rasterfile,
                                                'RASTER_BAND': 1,
                                                'COLUMN_PREFIX': '_',
                                                'STATISTICS': [2],
                                                'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT})

I tried the fields() extension but it only gives back the column names of the zonal statistics csv:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for field in result['OUTPUT'].fields():
   print(field)

<QgsField: T_k (string)>
<QgsField: Area (double)>
<QgsField: Perimeter (double)>
<QgsField: _mean (double)>

>Solution :

You can use:

# result['OUTPUT'] is a QgsVectorLayer

df = pd.DataFrame([feat.attributes() for feat in result['OUTPUT'].getFeatures()],
                  columns=[field.name() for field in result['OUTPUT'].fields()])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading