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?

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Jul 22, 2021 at 11:34
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. Commented Jul 22, 2021 at 11:48
  • my dataframe consists of double numbers and my header which are string values Commented Jul 22, 2021 at 11:57

1 Answer 1

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

answered Jul 22, 2021 at 12:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.