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?
-
See also this answer: gis.stackexchange.com/a/362988/202107NielsFlohr– NielsFlohr2022年06月26日 06:57:09 +00:00Commented Jun 26, 2022 at 6:57
1 Answer 1
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.