Summing field values with PyQGISSumming values from different intersecting/overlapping points in QGISQGIS:...

Can you tell from a blurry photo if focus was too close or too far?

Why is working on the same position for more than 15 years not a red flag?

Is a debit card dangerous in my situation?

Why Normality assumption in linear regression

Why would the Pakistan airspace closure cancel flights not headed to Pakistan itself?

Cookies - Should the toggles be on?

Writing a character who is going through a civilizing process without overdoing it?

Can a hotel cancel a confirmed reservation?

what does しにみえてる mean?

Why has the mole been redefined for 2019?

Citing paywalled articles accessed via illegal web sharing

Caruana vs Carlsen game 10 (WCC) why not 18...Nxb6?

Why exactly do action photographers need high fps burst cameras?

Why avoid shared user accounts?

Why isn't there a non-conducting core wire for high-frequency coil applications

Can we use the stored gravitational potential energy of a building to produce power?

Explain the objections to these measures against human trafficking

Porting Linux to another platform requirements

How to avoid being sexist when trying to employ someone to function in a very sexist environment?

Pronunciation of umlaut vowels in the history of German

Why publish a research paper when a blog post or a lecture slide can have more citation count than a journal paper?

What's a good word to describe a public place that looks like it wouldn't be rough?

If I delete my router's history can my ISP still provide it to my parents?

How to deal with an incendiary email that was recalled



Summing field values with PyQGIS


Summing values from different intersecting/overlapping points in QGISQGIS: SQL query within python console to sum a column based on values of other two columnsSum new values to existing attribute values in PyQGIS?PyQgis - Adding attributes to a POSTGIS layerWhy do I get different results from PyQGIS feature.geometry().type()?Why is QgsFeatureIterator returning bad data?Why can't I multiply values from column named 'length' using field calculator via PyQGIS?Adding field to shp subset layer using PyQGIS?How to get the selected value in a value map with Function Editor in QGIS 3.0.2?Summing attribute values of overlapping polyline portions in ArcGIS Desktop?Summing values from multiple polygons per neighbourhood in QGIS?Summing attribute values of overlapping polyline portions in QGIS 3.0.3Creating and updating a field from calculation













1















In QGIS 2.18 there is a shapefile with three fields accordingly



"id" | "Type" | "Value"


A sample of data: download



I want to get the total sum of all values in the field "Value". How can I achieve that in Python console?



Field "Value" maintains two types of data int() and NULL.



I was trying with a while-loop but it does not work



layer = qgis.utils.iface.activeLayer()

if not layer.isValid():
raise Exception('Layer is not valid')

features = layer.getFeatures()

for feat in features:
attr = feat.attributes()[2]

if attr == NULL:
continue

else:
total = 0
index = 0
while index < layer.featureCount():
total = total + int(attr)
index = index + 1
return(total)



Moreover, after executing @ahmadhanb's solution I received a correct number but
somehow with a strange output type, when print (type(sum(total))) it gives me
<type 'NoneType'>. What could be a problem?




How to achieve one number that gives the total sum of a whole field exclusive NULL-values?



References:




  • Find Neighbor Polygons in a Layer

  • Summing values from different intersecting/overlapping points in QGIS

  • Sum new values to existing attribute values in PyQGIS?

  • QGIS: SQL query within python console to sum a column based on values of other two columns










share|improve this question

























  • Try to place the print(total) out of the loop. This will give you one value which is the total value.

    – ahmadhanb
    17 hours ago











  • It gives one value, but a wrong one...

    – Taras
    17 hours ago






  • 1





    sum(filter(None,[f['Value'] for f in layer.getFeatures()]))

    – BERA
    17 hours ago











  • @Taras you can replace print(0) with continue to skip null values.

    – ahmadhanb
    17 hours ago








  • 1





    Thank you @ahmadhanb. Sorted with continue

    – Taras
    17 hours ago


















1















In QGIS 2.18 there is a shapefile with three fields accordingly



"id" | "Type" | "Value"


A sample of data: download



I want to get the total sum of all values in the field "Value". How can I achieve that in Python console?



Field "Value" maintains two types of data int() and NULL.



I was trying with a while-loop but it does not work



layer = qgis.utils.iface.activeLayer()

if not layer.isValid():
raise Exception('Layer is not valid')

features = layer.getFeatures()

for feat in features:
attr = feat.attributes()[2]

if attr == NULL:
continue

else:
total = 0
index = 0
while index < layer.featureCount():
total = total + int(attr)
index = index + 1
return(total)



Moreover, after executing @ahmadhanb's solution I received a correct number but
somehow with a strange output type, when print (type(sum(total))) it gives me
<type 'NoneType'>. What could be a problem?




How to achieve one number that gives the total sum of a whole field exclusive NULL-values?



References:




  • Find Neighbor Polygons in a Layer

  • Summing values from different intersecting/overlapping points in QGIS

  • Sum new values to existing attribute values in PyQGIS?

  • QGIS: SQL query within python console to sum a column based on values of other two columns










share|improve this question

























  • Try to place the print(total) out of the loop. This will give you one value which is the total value.

    – ahmadhanb
    17 hours ago











  • It gives one value, but a wrong one...

    – Taras
    17 hours ago






  • 1





    sum(filter(None,[f['Value'] for f in layer.getFeatures()]))

    – BERA
    17 hours ago











  • @Taras you can replace print(0) with continue to skip null values.

    – ahmadhanb
    17 hours ago








  • 1





    Thank you @ahmadhanb. Sorted with continue

    – Taras
    17 hours ago
















1












1








1








In QGIS 2.18 there is a shapefile with three fields accordingly



"id" | "Type" | "Value"


A sample of data: download



I want to get the total sum of all values in the field "Value". How can I achieve that in Python console?



Field "Value" maintains two types of data int() and NULL.



I was trying with a while-loop but it does not work



layer = qgis.utils.iface.activeLayer()

if not layer.isValid():
raise Exception('Layer is not valid')

features = layer.getFeatures()

for feat in features:
attr = feat.attributes()[2]

if attr == NULL:
continue

else:
total = 0
index = 0
while index < layer.featureCount():
total = total + int(attr)
index = index + 1
return(total)



Moreover, after executing @ahmadhanb's solution I received a correct number but
somehow with a strange output type, when print (type(sum(total))) it gives me
<type 'NoneType'>. What could be a problem?




How to achieve one number that gives the total sum of a whole field exclusive NULL-values?



References:




  • Find Neighbor Polygons in a Layer

  • Summing values from different intersecting/overlapping points in QGIS

  • Sum new values to existing attribute values in PyQGIS?

  • QGIS: SQL query within python console to sum a column based on values of other two columns










share|improve this question
















In QGIS 2.18 there is a shapefile with three fields accordingly



"id" | "Type" | "Value"


A sample of data: download



I want to get the total sum of all values in the field "Value". How can I achieve that in Python console?



Field "Value" maintains two types of data int() and NULL.



I was trying with a while-loop but it does not work



layer = qgis.utils.iface.activeLayer()

if not layer.isValid():
raise Exception('Layer is not valid')

features = layer.getFeatures()

for feat in features:
attr = feat.attributes()[2]

if attr == NULL:
continue

else:
total = 0
index = 0
while index < layer.featureCount():
total = total + int(attr)
index = index + 1
return(total)



Moreover, after executing @ahmadhanb's solution I received a correct number but
somehow with a strange output type, when print (type(sum(total))) it gives me
<type 'NoneType'>. What could be a problem?




How to achieve one number that gives the total sum of a whole field exclusive NULL-values?



References:




  • Find Neighbor Polygons in a Layer

  • Summing values from different intersecting/overlapping points in QGIS

  • Sum new values to existing attribute values in PyQGIS?

  • QGIS: SQL query within python console to sum a column based on values of other two columns







pyqgis sum






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 4 mins ago







Taras

















asked 17 hours ago









TarasTaras

2,1922624




2,1922624













  • Try to place the print(total) out of the loop. This will give you one value which is the total value.

    – ahmadhanb
    17 hours ago











  • It gives one value, but a wrong one...

    – Taras
    17 hours ago






  • 1





    sum(filter(None,[f['Value'] for f in layer.getFeatures()]))

    – BERA
    17 hours ago











  • @Taras you can replace print(0) with continue to skip null values.

    – ahmadhanb
    17 hours ago








  • 1





    Thank you @ahmadhanb. Sorted with continue

    – Taras
    17 hours ago





















  • Try to place the print(total) out of the loop. This will give you one value which is the total value.

    – ahmadhanb
    17 hours ago











  • It gives one value, but a wrong one...

    – Taras
    17 hours ago






  • 1





    sum(filter(None,[f['Value'] for f in layer.getFeatures()]))

    – BERA
    17 hours ago











  • @Taras you can replace print(0) with continue to skip null values.

    – ahmadhanb
    17 hours ago








  • 1





    Thank you @ahmadhanb. Sorted with continue

    – Taras
    17 hours ago



















Try to place the print(total) out of the loop. This will give you one value which is the total value.

– ahmadhanb
17 hours ago





Try to place the print(total) out of the loop. This will give you one value which is the total value.

– ahmadhanb
17 hours ago













It gives one value, but a wrong one...

– Taras
17 hours ago





It gives one value, but a wrong one...

– Taras
17 hours ago




1




1





sum(filter(None,[f['Value'] for f in layer.getFeatures()]))

– BERA
17 hours ago





sum(filter(None,[f['Value'] for f in layer.getFeatures()]))

– BERA
17 hours ago













@Taras you can replace print(0) with continue to skip null values.

– ahmadhanb
17 hours ago







@Taras you can replace print(0) with continue to skip null values.

– ahmadhanb
17 hours ago






1




1





Thank you @ahmadhanb. Sorted with continue

– Taras
17 hours ago







Thank you @ahmadhanb. Sorted with continue

– Taras
17 hours ago












1 Answer
1






active

oldest

votes


















1














In fact your code provides a double number to the actual value. For example, if the total number is 50, your code provides 100. I think the correct code should be something like this:



layer = qgis.utils.iface.activeLayer()

if not layer.isValid():
raise Exception('Layer is not valid')

features = layer.getFeatures()

total = []
for feat in features:
attr = feat.attributes()[2]

if attr == NULL:
continue

else:
total.append((int(attr)))
print(sum(total))


Add a total empty list outside the loop, and if the attr == NULL, it will skip the null values, and if there is a value in the attr it will be appended to the list. Then you can print the sum of the list outside the loop to get one value only.



Here is the screenshot of the output:



enter image description here






share|improve this answer


























  • Looks promising! The problem is that the output of print(type(sum(total))) is <type 'NoneType'>. I need to use it in some further calculations.

    – Taras
    16 hours ago











  • @Taras But I did not write print(type(sum(total))), I wrote print(sum(total)) which will provide an integer value. The output print(type(sum(total))) is <class 'int'> not <type 'NoneType'>

    – ahmadhanb
    16 hours ago













  • How can I use this value in my further calculations when the type that I do have is <type 'NoneType'>?

    – Taras
    16 hours ago













  • That is strange. Why do you get <type 'NoneType'>? I am getting integer output type.

    – ahmadhanb
    16 hours ago











  • Shouldnt if attr == NULL be if attr is None?

    – BERA
    16 hours ago













Your Answer








StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "79"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f313901%2fsumming-field-values-with-pyqgis%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














In fact your code provides a double number to the actual value. For example, if the total number is 50, your code provides 100. I think the correct code should be something like this:



layer = qgis.utils.iface.activeLayer()

if not layer.isValid():
raise Exception('Layer is not valid')

features = layer.getFeatures()

total = []
for feat in features:
attr = feat.attributes()[2]

if attr == NULL:
continue

else:
total.append((int(attr)))
print(sum(total))


Add a total empty list outside the loop, and if the attr == NULL, it will skip the null values, and if there is a value in the attr it will be appended to the list. Then you can print the sum of the list outside the loop to get one value only.



Here is the screenshot of the output:



enter image description here






share|improve this answer


























  • Looks promising! The problem is that the output of print(type(sum(total))) is <type 'NoneType'>. I need to use it in some further calculations.

    – Taras
    16 hours ago











  • @Taras But I did not write print(type(sum(total))), I wrote print(sum(total)) which will provide an integer value. The output print(type(sum(total))) is <class 'int'> not <type 'NoneType'>

    – ahmadhanb
    16 hours ago













  • How can I use this value in my further calculations when the type that I do have is <type 'NoneType'>?

    – Taras
    16 hours ago













  • That is strange. Why do you get <type 'NoneType'>? I am getting integer output type.

    – ahmadhanb
    16 hours ago











  • Shouldnt if attr == NULL be if attr is None?

    – BERA
    16 hours ago


















1














In fact your code provides a double number to the actual value. For example, if the total number is 50, your code provides 100. I think the correct code should be something like this:



layer = qgis.utils.iface.activeLayer()

if not layer.isValid():
raise Exception('Layer is not valid')

features = layer.getFeatures()

total = []
for feat in features:
attr = feat.attributes()[2]

if attr == NULL:
continue

else:
total.append((int(attr)))
print(sum(total))


Add a total empty list outside the loop, and if the attr == NULL, it will skip the null values, and if there is a value in the attr it will be appended to the list. Then you can print the sum of the list outside the loop to get one value only.



Here is the screenshot of the output:



enter image description here






share|improve this answer


























  • Looks promising! The problem is that the output of print(type(sum(total))) is <type 'NoneType'>. I need to use it in some further calculations.

    – Taras
    16 hours ago











  • @Taras But I did not write print(type(sum(total))), I wrote print(sum(total)) which will provide an integer value. The output print(type(sum(total))) is <class 'int'> not <type 'NoneType'>

    – ahmadhanb
    16 hours ago













  • How can I use this value in my further calculations when the type that I do have is <type 'NoneType'>?

    – Taras
    16 hours ago













  • That is strange. Why do you get <type 'NoneType'>? I am getting integer output type.

    – ahmadhanb
    16 hours ago











  • Shouldnt if attr == NULL be if attr is None?

    – BERA
    16 hours ago
















1












1








1







In fact your code provides a double number to the actual value. For example, if the total number is 50, your code provides 100. I think the correct code should be something like this:



layer = qgis.utils.iface.activeLayer()

if not layer.isValid():
raise Exception('Layer is not valid')

features = layer.getFeatures()

total = []
for feat in features:
attr = feat.attributes()[2]

if attr == NULL:
continue

else:
total.append((int(attr)))
print(sum(total))


Add a total empty list outside the loop, and if the attr == NULL, it will skip the null values, and if there is a value in the attr it will be appended to the list. Then you can print the sum of the list outside the loop to get one value only.



Here is the screenshot of the output:



enter image description here






share|improve this answer















In fact your code provides a double number to the actual value. For example, if the total number is 50, your code provides 100. I think the correct code should be something like this:



layer = qgis.utils.iface.activeLayer()

if not layer.isValid():
raise Exception('Layer is not valid')

features = layer.getFeatures()

total = []
for feat in features:
attr = feat.attributes()[2]

if attr == NULL:
continue

else:
total.append((int(attr)))
print(sum(total))


Add a total empty list outside the loop, and if the attr == NULL, it will skip the null values, and if there is a value in the attr it will be appended to the list. Then you can print the sum of the list outside the loop to get one value only.



Here is the screenshot of the output:



enter image description here







share|improve this answer














share|improve this answer



share|improve this answer








edited 16 hours ago

























answered 17 hours ago









ahmadhanbahmadhanb

22.8k32153




22.8k32153













  • Looks promising! The problem is that the output of print(type(sum(total))) is <type 'NoneType'>. I need to use it in some further calculations.

    – Taras
    16 hours ago











  • @Taras But I did not write print(type(sum(total))), I wrote print(sum(total)) which will provide an integer value. The output print(type(sum(total))) is <class 'int'> not <type 'NoneType'>

    – ahmadhanb
    16 hours ago













  • How can I use this value in my further calculations when the type that I do have is <type 'NoneType'>?

    – Taras
    16 hours ago













  • That is strange. Why do you get <type 'NoneType'>? I am getting integer output type.

    – ahmadhanb
    16 hours ago











  • Shouldnt if attr == NULL be if attr is None?

    – BERA
    16 hours ago





















  • Looks promising! The problem is that the output of print(type(sum(total))) is <type 'NoneType'>. I need to use it in some further calculations.

    – Taras
    16 hours ago











  • @Taras But I did not write print(type(sum(total))), I wrote print(sum(total)) which will provide an integer value. The output print(type(sum(total))) is <class 'int'> not <type 'NoneType'>

    – ahmadhanb
    16 hours ago













  • How can I use this value in my further calculations when the type that I do have is <type 'NoneType'>?

    – Taras
    16 hours ago













  • That is strange. Why do you get <type 'NoneType'>? I am getting integer output type.

    – ahmadhanb
    16 hours ago











  • Shouldnt if attr == NULL be if attr is None?

    – BERA
    16 hours ago



















Looks promising! The problem is that the output of print(type(sum(total))) is <type 'NoneType'>. I need to use it in some further calculations.

– Taras
16 hours ago





Looks promising! The problem is that the output of print(type(sum(total))) is <type 'NoneType'>. I need to use it in some further calculations.

– Taras
16 hours ago













@Taras But I did not write print(type(sum(total))), I wrote print(sum(total)) which will provide an integer value. The output print(type(sum(total))) is <class 'int'> not <type 'NoneType'>

– ahmadhanb
16 hours ago







@Taras But I did not write print(type(sum(total))), I wrote print(sum(total)) which will provide an integer value. The output print(type(sum(total))) is <class 'int'> not <type 'NoneType'>

– ahmadhanb
16 hours ago















How can I use this value in my further calculations when the type that I do have is <type 'NoneType'>?

– Taras
16 hours ago







How can I use this value in my further calculations when the type that I do have is <type 'NoneType'>?

– Taras
16 hours ago















That is strange. Why do you get <type 'NoneType'>? I am getting integer output type.

– ahmadhanb
16 hours ago





That is strange. Why do you get <type 'NoneType'>? I am getting integer output type.

– ahmadhanb
16 hours ago













Shouldnt if attr == NULL be if attr is None?

– BERA
16 hours ago







Shouldnt if attr == NULL be if attr is None?

– BERA
16 hours ago




















draft saved

draft discarded




















































Thanks for contributing an answer to Geographic Information Systems Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f313901%2fsumming-field-values-with-pyqgis%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Щит и меч (фильм) Содержание Названия серий | Сюжет |...

is 'sed' thread safeWhat should someone know about using Python scripts in the shell?Nexenta bash script uses...

Meter-Bus Содержание Параметры шины | Стандартизация |...