I'm trying to sum new values from a list in one loop to the existing attribute values (not in a new column, but in the exiting attribute values itselfs).
def radiusDivider(dist):
try:
itlayer = QgsMapLayerRegistry.instance().mapLayersByName('itpoint')[0]
print ('itpoint-layer found')
prov = itlayer.dataProvider()
itlayer.startEditing()
if prov.fieldNameIndex("score") == -1:
prov.addAttributes( [ QgsField("score", QVariant.Double)])
print("field added")
else:
print ("field already exists")
itlayer.updateFields()
it = itlayer.getFeatures()
count = 0
for feat in it:
itlayer.changeAttributeValue(feat.id(), 2, 0)
#print ("changing attribute")
count += 1
itlayer.commitChanges()
for radius in range (50, dist, 50):
addToScore(radius)
except:
print ("itpoint layer does not exist")
... a lot of stuff happens in the "addToScore function", but the only important thing is, that I append a calculated “score“ to the "scorelist" for each point of the "itlayer". I'm trying to add in the following code the calculated current score to the existing score (from eventual previous runs) to get after all needed iterations of calculation the final score. :-) ...
def addToScore(bufDist):
#...
scorelist.append(calc)
#...
itlayer.startEditing()
itlayer.updateFields()
it = itlayer.getFeatures()
count = 0
idx = itlayer.fieldNameIndex('score')
for feat in it:
oldscore = feat.attributes()[idx]
print ("old:", oldscore)
print ("current:", scorelist[count])
newscore = list(np.asarray(oldscore) + (scorelist))
print ("new:", newscore)
#prints above show that it works perfectly, so I would guess in the following line is something wrong?
for ft in it:
itlayer.changeAttributeValue(ft.id(), 2, (newscore[count]))
count += 1
#print ("changing attribute")
itlayer.commitChanges()
itlayer.removeSelection()
#inputlayer.selectByIds(true, 1)
except IndexError:
print ('itpoint does not exist')
Edit 1:
I checked and only the values in "scorelist" have type 'int', the other values from "oldscore" and "newscore" have type 'numpy.64int'...? Is this the reason it doesn't work and how do I solve it?
Answer
Yes it was the type, which was silently causing trouble! I fixed it this way:
#...
itlayer.startEditing()
itlayer.updateFields()
it = itlayer.getFeatures()
count = 0
idx = itlayer.fieldNameIndex('score')
for feat in it:
oldscore = feat.attributes()[idx]
print ("old:", oldscore)
print ("current:", scorelist[count])
newscore = (oldscore+ scorelist[count])
print ('new:', newscore,'with type:', type(newscore))
itlayer.changeAttributeValue(feat.id(), 2, (newscore))
count += 1
print ("changing attribute")
itlayer.commitChanges()
#...
"newscore" has now type 'int' (and not type 'numpy.64int') as it should and it works perfectly.
No comments:
Post a Comment