1

I am trying to develop a processing plugin using "Create New Script from Template".

In this plugin I have created a pandas dataframe. Assuming the df looks like this:

C1 C2
0.25 0.84
0.36 0.4

Can I transform this df into features' attribute table?

Can I export this attribute table as a layer?

2
  • Yes it's a pandas daaframe. I want this specific one to be transformed into features. C1&C2 will be my headers in the attribute table and 0.25,0.84 will be feature 1 and 0.36,0.4 will be feature 2.
    – Annie S.
    Jul 22 at 11:48
  • my dataframe consists of double numbers and my header which are string values
    – Annie S.
    Jul 22 at 11:57
2

This should work for your specific case:

import pandas as pd

flist=['C1','C2']
df = pd.DataFrame.from_records(data = [(0.25,0.84),(0.36,0.4)], columns=flist)

vl = QgsVectorLayer("None", "temporary_table", "memory") #Adjust this line if you dont want a temp table
pr = vl.dataProvider()
vl.startEditing()
fieldlist = [QgsField(fieldname, QVariant.Double) for fieldname in flist]

pr.addAttributes(fieldlist)
vl.updateFields()

for i in df.index.to_list():
    fet = QgsFeature()
    newrow = df[flist].iloc[i].tolist()
    fet.setAttributes(newrow)
    pr.addFeatures([ fet ])
vl.commitChanges()

QgsProject.instance().addMapLayer(vl)

enter image description here

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.