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.

1
  • 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? Oct 14, 2020 at 22:50

1 Answer 1

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)
2
  • 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, 2020 at 9: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. Oct 15, 2020 at 10:06

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.