8

I am writing a python script for QGIS.

I have a pandas dataframe that I would like to use in order to create a QgsVectorLayer.

At the moment I am saving the data frame into a .csv and then I load it:

name_csv = 'virtuali.csv' 
df.to_csv(name_csv,index=False)
path = "file:///" + name_csv + "?encoding=%s&delimiter=%s&xField=%s&yField=%s&crs=%s" % ("UTF-8",",", "Longitudine", "Latitudine","epsg:4326")
mylayer = QgsVectorLayer(path, "pandas_layer", "delimitedtext")

Is there a way to create the Pandas dataframe directly without saving and reloading it?

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Nov 25, 2019 at 9:30
1

1 Answer 1

9

Your method is the simplest. However, there is an alternative by creating a new layer in QGIS and completing it by browsing your dataframe pandas.

import pandas as pd 
# Declaration of my pandas dataframe 
d = {'col1' : [1,2], 'col2': [3,4]}
df = pd.DataFrame(data=d)
# Creation of my QgsVectorLayer with no geometry 
temp = QgsVectorLayer("none","result","memory")
temp_data = temp.dataProvider()
# Start of the edition 
temp.startEditing()
# Creation of my fields 
for head in df : 
 myField = QgsField( head, QVariant.Double )
 temp.addAttribute(myField)
# Update 
temp.updateFields()
# Addition of features
# [1] because i don't want the indexes 
for row in df.itertuples():
 f = QgsFeature()
 f.setAttributes([row[1],row[2]])
 temp.addFeature(f)
 print(row)
# saving changes and adding the layer
temp.commitChanges()
QgsProject.instance().addMapLayer(temp)

The above example can be optimized.

answered Nov 25, 2019 at 14:19

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.