7

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?

1

1 Answer 1

8

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.