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?
asked Jul 22, 2021 at 11:34
-
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.– Annie S.2021年07月22日 11:48:55 +00:00Commented Jul 22, 2021 at 11:48
-
my dataframe consists of double numbers and my header which are string valuesAnnie S.– Annie S.2021年07月22日 11:57:32 +00:00Commented Jul 22, 2021 at 11:57
1 Answer 1
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)
answered Jul 22, 2021 at 12:08
Explore related questions
See similar questions with these tags.
lang-py