4

Iт QGIS 3.10 I have imported a CSV which contains a column of numeric data (let's call this attribute "x"). However, it is imported automatically as strings. I can easily create a new field by clicking the Field Calculator and typing to_real("x").

Because I need to repeat this many times, I would like to use PyQGIS to do this.

I've been trying various ways but I still can't get it to work. For example, I was following this: Struggling to use Field Calculator - PyQGIS

Could someone please tell me what I did wrong?

#import data
csv_file = QgsVectorLayer(path_to_csv, 'nameoflayer')
QgsProject.instance().addMapLayer(csv_file)

csv = QgsProject.instance().mapLayersByName('nameoflayer')[0]

#start editing this layer with edit(csv): for feature in selected_feature: feature.setAttribute(feature.fieldNameIndex('newfieldname'), to_real(feature['x'])) updateFeature(feature)

There is no error message but I can't see the new column called "newfieldname" when I open the attribute table after running the above code.

Taras
  • 32,823
  • 4
  • 66
  • 137
Jade
  • 43
  • 2
  • Does your table already have newfieldname or do you want to add it using PyQGIS? Do you define selected_feature before using in for loop? – Kadir Şahbaz Oct 14 '20 at 22:50

1 Answers1

4

to_real is a function belonging to Field Calculator. Its Python equivalent is float. I assume "newfieldname" already exists in the attribute table. Use this script:

csv = QgsProject.instance().mapLayersByName('nameoflayer')[0]

with edit(csv): csv.addAttribute(QgsField('newfieldname', QVariant.Double))

for feature in csv.getFeatures(): # OR csv.selectedFeatures():
    feature['newfieldname'] = float(feature['x'])
    csv.updateFeature(feature)

Taras
  • 32,823
  • 4
  • 66
  • 137
Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
  • Thank you! No actually newfieldname does not exist yet! And I did try creating one by using the code below, but it's also not working :( It doesn't show up. csv.startEditing() csv.addAttributes([QgsField('newfieldname', QVariant.Int)]) csv.commitChanges() – Jade Oct 15 '20 at 09:41
  • You should use addAttribute instead of addAttributes under edit. Also, when using addAttribute you don't need to use the brackets [...]. And since you use edit, you don't need to use commitChanges(). I've edited the answer. – Kadir Şahbaz Oct 15 '20 at 10:06