Is there any pythonic way to find average of specific tuple elements in array?sum of small double numbers...

Why must Chinese maps be obfuscated?

Contradiction proof for inequality of P and NP?

How does Captain America channel this power?

Is it idiomatic to construct against `this`

Function pointer with named arguments?

Alignment of various blocks in tikz

What is causing the white spot to appear in some of my pictures

bldc motor, esc and battery draw, nominal vs peak

Mistake in years of experience in resume?

What does ゆーか mean?

How do I deal with a coworker that keeps asking to make small superficial changes to a report, and it is seriously triggering my anxiety?

Like totally amazing interchangeable sister outfits II: The Revenge

Critique of timeline aesthetic

Relationship between strut and baselineskip

Is Diceware more secure than a long passphrase?

What happened to Captain America in Endgame?

Could the terminal length of components like resistors be reduced?

Can someone publish a story that happened to you?

How come there are so many candidates for the 2020 Democratic party presidential nomination?

Can SQL Server create collisions in system generated constraint names?

can anyone help me with this awful query plan?

How can I practically buy stocks?

How to display Aura JS Errors Lightning Out

Why did C use the -> operator instead of reusing the . operator?



Is there any pythonic way to find average of specific tuple elements in array?


sum of small double numbers c++Is there a way to run Python on Android?Finding the index of an item given a list containing it in PythonPHP: Delete an element from an arrayWhat's the simplest way to print a Java array?How to insert an item into an array at a specific index (JavaScript)?Getting the last element of a list in PythonHow do I get the number of elements in a list in Python?What are “named tuples” in Python?How do I remove a particular element from an array in JavaScript?How can I add new array elements at the beginning of an array in Javascript?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







17















I want to write this code as pythonic. My real array much bigger than this example.



( 5+10+20+3+2 ) / 5




print(np.mean(array,key=lambda x:x[1]))
TypeError: mean() got an unexpected keyword argument 'key'




array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]

sum = 0
for i in range(len(array)):
sum = sum + array[i][1]

average = sum / len(array)
print(average)

import numpy as np
print(np.mean(array,key=lambda x:x[1]))


How can avoid this?
I want to use second example.










share|improve this question

























  • What version of Python are you using?

    – Peter Wood
    yesterday






  • 1





    @PeterWood python 3.7

    – Şevval Kahraman
    yesterday


















17















I want to write this code as pythonic. My real array much bigger than this example.



( 5+10+20+3+2 ) / 5




print(np.mean(array,key=lambda x:x[1]))
TypeError: mean() got an unexpected keyword argument 'key'




array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]

sum = 0
for i in range(len(array)):
sum = sum + array[i][1]

average = sum / len(array)
print(average)

import numpy as np
print(np.mean(array,key=lambda x:x[1]))


How can avoid this?
I want to use second example.










share|improve this question

























  • What version of Python are you using?

    – Peter Wood
    yesterday






  • 1





    @PeterWood python 3.7

    – Şevval Kahraman
    yesterday














17












17








17


1






I want to write this code as pythonic. My real array much bigger than this example.



( 5+10+20+3+2 ) / 5




print(np.mean(array,key=lambda x:x[1]))
TypeError: mean() got an unexpected keyword argument 'key'




array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]

sum = 0
for i in range(len(array)):
sum = sum + array[i][1]

average = sum / len(array)
print(average)

import numpy as np
print(np.mean(array,key=lambda x:x[1]))


How can avoid this?
I want to use second example.










share|improve this question
















I want to write this code as pythonic. My real array much bigger than this example.



( 5+10+20+3+2 ) / 5




print(np.mean(array,key=lambda x:x[1]))
TypeError: mean() got an unexpected keyword argument 'key'




array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]

sum = 0
for i in range(len(array)):
sum = sum + array[i][1]

average = sum / len(array)
print(average)

import numpy as np
print(np.mean(array,key=lambda x:x[1]))


How can avoid this?
I want to use second example.







python arrays python-3.x tuples average






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited yesterday









ruohola

2,016424




2,016424










asked yesterday









Şevval KahramanŞevval Kahraman

1407




1407













  • What version of Python are you using?

    – Peter Wood
    yesterday






  • 1





    @PeterWood python 3.7

    – Şevval Kahraman
    yesterday



















  • What version of Python are you using?

    – Peter Wood
    yesterday






  • 1





    @PeterWood python 3.7

    – Şevval Kahraman
    yesterday

















What version of Python are you using?

– Peter Wood
yesterday





What version of Python are you using?

– Peter Wood
yesterday




1




1





@PeterWood python 3.7

– Şevval Kahraman
yesterday





@PeterWood python 3.7

– Şevval Kahraman
yesterday












9 Answers
9






active

oldest

votes


















22














If you are using Python 3.4 or above, you could use the statistics module:



from statistics import mean

average = mean(value[1] for value in array)


Or if you're using a version of Python older than 3.4:



average = sum(value[1] for value in array) / len(array)


These solutions both use a nice feature of Python called a generator expression. The loop



value[1] for value in array


creates a new sequence in a timely and memory efficient manner. See PEP 289 -- Generator Expressions.



If you're using Python 2, and you're summing integers, we will have integer division, which will truncate the result, e.g:



>>> 25 / 4
6

>>> 25 / float(4)
6.25


To ensure we don't have integer division we could set the starting value of sum to be the float value 0.0. However, this also means we have to make the generator expression explicit with parentheses, otherwise it's a syntax error, and it's less pretty, as noted in the comments:



average = sum((value[1] for value in array), 0.0) / len(array)


It's probably best to use fsum from the math module which will return a float:



from math import fsum

average = fsum(value[1] for value in array) / len(array)





share|improve this answer


























  • I realised there are better ways to do the Python 2 code. sum takes an argument for the starting value. If you pass 0.0 to it, then the numerator will always be floating point, nothing to worry about. Also, there is a function in the math module, fsum.

    – Peter Wood
    yesterday






  • 5





    I would say the float casting way is little bit more self-explanatory than passing a weird 0.0 value argument for the sum.

    – ruohola
    yesterday













  • @ruohola I think using fsum is probably best for Python 2.

    – Peter Wood
    yesterday






  • 1





    Can't you from __future__ import division?

    – DanielSank
    yesterday













  • @DanielSank yes, that's another option. Another advantage of using fsum, if you're summing floats, is it keeps track of partial sums, which compensates for lack of precision in the floating point representation. So, if we stay using fsum we don't need to think about integer division at all, and are generally the better solution too. See my answer about Kahan Summation in c++.

    – Peter Wood
    yesterday



















3














If you do want to use numpy, cast it to a numpy.array and select the axis you want using numpy indexing:



import numpy as np

array = np.array([('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)])
print(array[:,1].astype(float).mean())
# 8.0


The cast to a numeric type is needed because the original array contains both strings and numbers and is therefore of type object. In this case you could use float or int, it makes no difference.






share|improve this answer

































    2














    With pure Python:



    from operator import itemgetter

    acc = 0
    count = 0

    for value in map(itemgetter(1), array):
    acc += value
    count += 1

    mean = acc / count


    An iterative approach can be preferable if your data cannot fit in memory as a list (since you said it was big). If it can, prefer a declarative approach:



    data = [sub[1] for sub in array]
    mean = sum(data) / len(data)


    If you are open to using numpy, I find this cleaner:



    a = np.array(array)

    mean = a[:, 1].astype(int).mean()





    share|improve this answer

































      2














      You can simply use:



      print(sum(tup[1] for tup in array) / len(array))


      Or for Python 2:



      print(sum(tup[1] for tup in array) / float(len(array)))


      Or little bit more concisely for Python 2:



      from math import fsum

      print(fsum(tup[1] for tup in array) / len(array))





      share|improve this answer


























      • it gives this error : 'int' object is not callable

        – Şevval Kahraman
        yesterday











      • @ŞevvalKahraman it gives no errors for me with your example array, you probably have a typo somewhere.

        – ruohola
        yesterday













      • @ruohola The reason it works for the example is it's 40 / 5 which gives 8 with no remainder. In Python 2, with different numbers, it could truncate the answer.

        – Peter Wood
        yesterday











      • @PeterWood it will not truncate anything if you use the float(len(array)) casting when using Python 2. Anyways it shouldn't even matter since this question was for Python 3.x.

        – ruohola
        yesterday













      • As it's python 3, just use statistics.mean.

        – Peter Wood
        yesterday



















      2














      If you're open to more golf-like solutions, you can transpose your array with vanilla python, get a list of just the numbers, and calculate the mean with



      sum(zip(*array)[1])/len(array)





      share|improve this answer








      New contributor




      Nick Amin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




























        1














        you can use map instead of list comprehension



        sum(map(lambda x:int(x[1]), array)) / len(array)


        or functools.reduce (if you use Python2.X just reduce not functools.reduce)



        import functools
        functools.reduce(lambda acc, y: acc + y[1], array, 0) / len(array)





        share|improve this answer


























        • first one gives this error : 'int' object is not callable

          – Şevval Kahraman
          yesterday











        • @ŞevvalKahraman if array is defined as shown in your question - the first one give 8.0 (tested & verified on same version). So either the array your using has a different value somewhere or you made a typo

          – JGreenwell
          yesterday











        • x[1] is already an integer, why do you need to call int()?

          – Barmar
          yesterday











        • Using a lambda is 30% slower than a generator comprehension. But if you prefer map, I recommend using operator.itemgetter(1) instead of the lambda.

          – Mateen Ulhaq
          yesterday













        • Similarly, functools.reduce is 72% slower than a generator comprehension and sum.

          – Mateen Ulhaq
          yesterday





















        0














        You could use map:



        np.mean(list(map(lambda x: x[1], array)))






        share|improve this answer































          0














          Just find the average using sum and number of elements of the list.



          array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
          avg = float(sum(value[1] for value in array)) / float(len(array))
          print(avg)
          #8.0





          share|improve this answer

































            0














            One way would be to define a structured array from the list of tuples:



            l = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
            a = np.array(l, dtype=([('str', '<U1'), ('num', '<i4')]))


            And then take the np.mean of the numerical field, i.e the second element in the tuples:



            np.mean(a['num'])
            # 8.0





            share|improve this answer


























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              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: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              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%2fstackoverflow.com%2fquestions%2f55843611%2fis-there-any-pythonic-way-to-find-average-of-specific-tuple-elements-in-array%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              9 Answers
              9






              active

              oldest

              votes








              9 Answers
              9






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              22














              If you are using Python 3.4 or above, you could use the statistics module:



              from statistics import mean

              average = mean(value[1] for value in array)


              Or if you're using a version of Python older than 3.4:



              average = sum(value[1] for value in array) / len(array)


              These solutions both use a nice feature of Python called a generator expression. The loop



              value[1] for value in array


              creates a new sequence in a timely and memory efficient manner. See PEP 289 -- Generator Expressions.



              If you're using Python 2, and you're summing integers, we will have integer division, which will truncate the result, e.g:



              >>> 25 / 4
              6

              >>> 25 / float(4)
              6.25


              To ensure we don't have integer division we could set the starting value of sum to be the float value 0.0. However, this also means we have to make the generator expression explicit with parentheses, otherwise it's a syntax error, and it's less pretty, as noted in the comments:



              average = sum((value[1] for value in array), 0.0) / len(array)


              It's probably best to use fsum from the math module which will return a float:



              from math import fsum

              average = fsum(value[1] for value in array) / len(array)





              share|improve this answer


























              • I realised there are better ways to do the Python 2 code. sum takes an argument for the starting value. If you pass 0.0 to it, then the numerator will always be floating point, nothing to worry about. Also, there is a function in the math module, fsum.

                – Peter Wood
                yesterday






              • 5





                I would say the float casting way is little bit more self-explanatory than passing a weird 0.0 value argument for the sum.

                – ruohola
                yesterday













              • @ruohola I think using fsum is probably best for Python 2.

                – Peter Wood
                yesterday






              • 1





                Can't you from __future__ import division?

                – DanielSank
                yesterday













              • @DanielSank yes, that's another option. Another advantage of using fsum, if you're summing floats, is it keeps track of partial sums, which compensates for lack of precision in the floating point representation. So, if we stay using fsum we don't need to think about integer division at all, and are generally the better solution too. See my answer about Kahan Summation in c++.

                – Peter Wood
                yesterday
















              22














              If you are using Python 3.4 or above, you could use the statistics module:



              from statistics import mean

              average = mean(value[1] for value in array)


              Or if you're using a version of Python older than 3.4:



              average = sum(value[1] for value in array) / len(array)


              These solutions both use a nice feature of Python called a generator expression. The loop



              value[1] for value in array


              creates a new sequence in a timely and memory efficient manner. See PEP 289 -- Generator Expressions.



              If you're using Python 2, and you're summing integers, we will have integer division, which will truncate the result, e.g:



              >>> 25 / 4
              6

              >>> 25 / float(4)
              6.25


              To ensure we don't have integer division we could set the starting value of sum to be the float value 0.0. However, this also means we have to make the generator expression explicit with parentheses, otherwise it's a syntax error, and it's less pretty, as noted in the comments:



              average = sum((value[1] for value in array), 0.0) / len(array)


              It's probably best to use fsum from the math module which will return a float:



              from math import fsum

              average = fsum(value[1] for value in array) / len(array)





              share|improve this answer


























              • I realised there are better ways to do the Python 2 code. sum takes an argument for the starting value. If you pass 0.0 to it, then the numerator will always be floating point, nothing to worry about. Also, there is a function in the math module, fsum.

                – Peter Wood
                yesterday






              • 5





                I would say the float casting way is little bit more self-explanatory than passing a weird 0.0 value argument for the sum.

                – ruohola
                yesterday













              • @ruohola I think using fsum is probably best for Python 2.

                – Peter Wood
                yesterday






              • 1





                Can't you from __future__ import division?

                – DanielSank
                yesterday













              • @DanielSank yes, that's another option. Another advantage of using fsum, if you're summing floats, is it keeps track of partial sums, which compensates for lack of precision in the floating point representation. So, if we stay using fsum we don't need to think about integer division at all, and are generally the better solution too. See my answer about Kahan Summation in c++.

                – Peter Wood
                yesterday














              22












              22








              22







              If you are using Python 3.4 or above, you could use the statistics module:



              from statistics import mean

              average = mean(value[1] for value in array)


              Or if you're using a version of Python older than 3.4:



              average = sum(value[1] for value in array) / len(array)


              These solutions both use a nice feature of Python called a generator expression. The loop



              value[1] for value in array


              creates a new sequence in a timely and memory efficient manner. See PEP 289 -- Generator Expressions.



              If you're using Python 2, and you're summing integers, we will have integer division, which will truncate the result, e.g:



              >>> 25 / 4
              6

              >>> 25 / float(4)
              6.25


              To ensure we don't have integer division we could set the starting value of sum to be the float value 0.0. However, this also means we have to make the generator expression explicit with parentheses, otherwise it's a syntax error, and it's less pretty, as noted in the comments:



              average = sum((value[1] for value in array), 0.0) / len(array)


              It's probably best to use fsum from the math module which will return a float:



              from math import fsum

              average = fsum(value[1] for value in array) / len(array)





              share|improve this answer















              If you are using Python 3.4 or above, you could use the statistics module:



              from statistics import mean

              average = mean(value[1] for value in array)


              Or if you're using a version of Python older than 3.4:



              average = sum(value[1] for value in array) / len(array)


              These solutions both use a nice feature of Python called a generator expression. The loop



              value[1] for value in array


              creates a new sequence in a timely and memory efficient manner. See PEP 289 -- Generator Expressions.



              If you're using Python 2, and you're summing integers, we will have integer division, which will truncate the result, e.g:



              >>> 25 / 4
              6

              >>> 25 / float(4)
              6.25


              To ensure we don't have integer division we could set the starting value of sum to be the float value 0.0. However, this also means we have to make the generator expression explicit with parentheses, otherwise it's a syntax error, and it's less pretty, as noted in the comments:



              average = sum((value[1] for value in array), 0.0) / len(array)


              It's probably best to use fsum from the math module which will return a float:



              from math import fsum

              average = fsum(value[1] for value in array) / len(array)






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 19 hours ago

























              answered yesterday









              Peter WoodPeter Wood

              16.9k33877




              16.9k33877













              • I realised there are better ways to do the Python 2 code. sum takes an argument for the starting value. If you pass 0.0 to it, then the numerator will always be floating point, nothing to worry about. Also, there is a function in the math module, fsum.

                – Peter Wood
                yesterday






              • 5





                I would say the float casting way is little bit more self-explanatory than passing a weird 0.0 value argument for the sum.

                – ruohola
                yesterday













              • @ruohola I think using fsum is probably best for Python 2.

                – Peter Wood
                yesterday






              • 1





                Can't you from __future__ import division?

                – DanielSank
                yesterday













              • @DanielSank yes, that's another option. Another advantage of using fsum, if you're summing floats, is it keeps track of partial sums, which compensates for lack of precision in the floating point representation. So, if we stay using fsum we don't need to think about integer division at all, and are generally the better solution too. See my answer about Kahan Summation in c++.

                – Peter Wood
                yesterday



















              • I realised there are better ways to do the Python 2 code. sum takes an argument for the starting value. If you pass 0.0 to it, then the numerator will always be floating point, nothing to worry about. Also, there is a function in the math module, fsum.

                – Peter Wood
                yesterday






              • 5





                I would say the float casting way is little bit more self-explanatory than passing a weird 0.0 value argument for the sum.

                – ruohola
                yesterday













              • @ruohola I think using fsum is probably best for Python 2.

                – Peter Wood
                yesterday






              • 1





                Can't you from __future__ import division?

                – DanielSank
                yesterday













              • @DanielSank yes, that's another option. Another advantage of using fsum, if you're summing floats, is it keeps track of partial sums, which compensates for lack of precision in the floating point representation. So, if we stay using fsum we don't need to think about integer division at all, and are generally the better solution too. See my answer about Kahan Summation in c++.

                – Peter Wood
                yesterday

















              I realised there are better ways to do the Python 2 code. sum takes an argument for the starting value. If you pass 0.0 to it, then the numerator will always be floating point, nothing to worry about. Also, there is a function in the math module, fsum.

              – Peter Wood
              yesterday





              I realised there are better ways to do the Python 2 code. sum takes an argument for the starting value. If you pass 0.0 to it, then the numerator will always be floating point, nothing to worry about. Also, there is a function in the math module, fsum.

              – Peter Wood
              yesterday




              5




              5





              I would say the float casting way is little bit more self-explanatory than passing a weird 0.0 value argument for the sum.

              – ruohola
              yesterday







              I would say the float casting way is little bit more self-explanatory than passing a weird 0.0 value argument for the sum.

              – ruohola
              yesterday















              @ruohola I think using fsum is probably best for Python 2.

              – Peter Wood
              yesterday





              @ruohola I think using fsum is probably best for Python 2.

              – Peter Wood
              yesterday




              1




              1





              Can't you from __future__ import division?

              – DanielSank
              yesterday







              Can't you from __future__ import division?

              – DanielSank
              yesterday















              @DanielSank yes, that's another option. Another advantage of using fsum, if you're summing floats, is it keeps track of partial sums, which compensates for lack of precision in the floating point representation. So, if we stay using fsum we don't need to think about integer division at all, and are generally the better solution too. See my answer about Kahan Summation in c++.

              – Peter Wood
              yesterday





              @DanielSank yes, that's another option. Another advantage of using fsum, if you're summing floats, is it keeps track of partial sums, which compensates for lack of precision in the floating point representation. So, if we stay using fsum we don't need to think about integer division at all, and are generally the better solution too. See my answer about Kahan Summation in c++.

              – Peter Wood
              yesterday













              3














              If you do want to use numpy, cast it to a numpy.array and select the axis you want using numpy indexing:



              import numpy as np

              array = np.array([('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)])
              print(array[:,1].astype(float).mean())
              # 8.0


              The cast to a numeric type is needed because the original array contains both strings and numbers and is therefore of type object. In this case you could use float or int, it makes no difference.






              share|improve this answer






























                3














                If you do want to use numpy, cast it to a numpy.array and select the axis you want using numpy indexing:



                import numpy as np

                array = np.array([('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)])
                print(array[:,1].astype(float).mean())
                # 8.0


                The cast to a numeric type is needed because the original array contains both strings and numbers and is therefore of type object. In this case you could use float or int, it makes no difference.






                share|improve this answer




























                  3












                  3








                  3







                  If you do want to use numpy, cast it to a numpy.array and select the axis you want using numpy indexing:



                  import numpy as np

                  array = np.array([('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)])
                  print(array[:,1].astype(float).mean())
                  # 8.0


                  The cast to a numeric type is needed because the original array contains both strings and numbers and is therefore of type object. In this case you could use float or int, it makes no difference.






                  share|improve this answer















                  If you do want to use numpy, cast it to a numpy.array and select the axis you want using numpy indexing:



                  import numpy as np

                  array = np.array([('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)])
                  print(array[:,1].astype(float).mean())
                  # 8.0


                  The cast to a numeric type is needed because the original array contains both strings and numbers and is therefore of type object. In this case you could use float or int, it makes no difference.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited yesterday

























                  answered yesterday









                  GraipherGraipher

                  4,7321634




                  4,7321634























                      2














                      With pure Python:



                      from operator import itemgetter

                      acc = 0
                      count = 0

                      for value in map(itemgetter(1), array):
                      acc += value
                      count += 1

                      mean = acc / count


                      An iterative approach can be preferable if your data cannot fit in memory as a list (since you said it was big). If it can, prefer a declarative approach:



                      data = [sub[1] for sub in array]
                      mean = sum(data) / len(data)


                      If you are open to using numpy, I find this cleaner:



                      a = np.array(array)

                      mean = a[:, 1].astype(int).mean()





                      share|improve this answer






























                        2














                        With pure Python:



                        from operator import itemgetter

                        acc = 0
                        count = 0

                        for value in map(itemgetter(1), array):
                        acc += value
                        count += 1

                        mean = acc / count


                        An iterative approach can be preferable if your data cannot fit in memory as a list (since you said it was big). If it can, prefer a declarative approach:



                        data = [sub[1] for sub in array]
                        mean = sum(data) / len(data)


                        If you are open to using numpy, I find this cleaner:



                        a = np.array(array)

                        mean = a[:, 1].astype(int).mean()





                        share|improve this answer




























                          2












                          2








                          2







                          With pure Python:



                          from operator import itemgetter

                          acc = 0
                          count = 0

                          for value in map(itemgetter(1), array):
                          acc += value
                          count += 1

                          mean = acc / count


                          An iterative approach can be preferable if your data cannot fit in memory as a list (since you said it was big). If it can, prefer a declarative approach:



                          data = [sub[1] for sub in array]
                          mean = sum(data) / len(data)


                          If you are open to using numpy, I find this cleaner:



                          a = np.array(array)

                          mean = a[:, 1].astype(int).mean()





                          share|improve this answer















                          With pure Python:



                          from operator import itemgetter

                          acc = 0
                          count = 0

                          for value in map(itemgetter(1), array):
                          acc += value
                          count += 1

                          mean = acc / count


                          An iterative approach can be preferable if your data cannot fit in memory as a list (since you said it was big). If it can, prefer a declarative approach:



                          data = [sub[1] for sub in array]
                          mean = sum(data) / len(data)


                          If you are open to using numpy, I find this cleaner:



                          a = np.array(array)

                          mean = a[:, 1].astype(int).mean()






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited yesterday

























                          answered yesterday









                          gmdsgmds

                          8,223932




                          8,223932























                              2














                              You can simply use:



                              print(sum(tup[1] for tup in array) / len(array))


                              Or for Python 2:



                              print(sum(tup[1] for tup in array) / float(len(array)))


                              Or little bit more concisely for Python 2:



                              from math import fsum

                              print(fsum(tup[1] for tup in array) / len(array))





                              share|improve this answer


























                              • it gives this error : 'int' object is not callable

                                – Şevval Kahraman
                                yesterday











                              • @ŞevvalKahraman it gives no errors for me with your example array, you probably have a typo somewhere.

                                – ruohola
                                yesterday













                              • @ruohola The reason it works for the example is it's 40 / 5 which gives 8 with no remainder. In Python 2, with different numbers, it could truncate the answer.

                                – Peter Wood
                                yesterday











                              • @PeterWood it will not truncate anything if you use the float(len(array)) casting when using Python 2. Anyways it shouldn't even matter since this question was for Python 3.x.

                                – ruohola
                                yesterday













                              • As it's python 3, just use statistics.mean.

                                – Peter Wood
                                yesterday
















                              2














                              You can simply use:



                              print(sum(tup[1] for tup in array) / len(array))


                              Or for Python 2:



                              print(sum(tup[1] for tup in array) / float(len(array)))


                              Or little bit more concisely for Python 2:



                              from math import fsum

                              print(fsum(tup[1] for tup in array) / len(array))





                              share|improve this answer


























                              • it gives this error : 'int' object is not callable

                                – Şevval Kahraman
                                yesterday











                              • @ŞevvalKahraman it gives no errors for me with your example array, you probably have a typo somewhere.

                                – ruohola
                                yesterday













                              • @ruohola The reason it works for the example is it's 40 / 5 which gives 8 with no remainder. In Python 2, with different numbers, it could truncate the answer.

                                – Peter Wood
                                yesterday











                              • @PeterWood it will not truncate anything if you use the float(len(array)) casting when using Python 2. Anyways it shouldn't even matter since this question was for Python 3.x.

                                – ruohola
                                yesterday













                              • As it's python 3, just use statistics.mean.

                                – Peter Wood
                                yesterday














                              2












                              2








                              2







                              You can simply use:



                              print(sum(tup[1] for tup in array) / len(array))


                              Or for Python 2:



                              print(sum(tup[1] for tup in array) / float(len(array)))


                              Or little bit more concisely for Python 2:



                              from math import fsum

                              print(fsum(tup[1] for tup in array) / len(array))





                              share|improve this answer















                              You can simply use:



                              print(sum(tup[1] for tup in array) / len(array))


                              Or for Python 2:



                              print(sum(tup[1] for tup in array) / float(len(array)))


                              Or little bit more concisely for Python 2:



                              from math import fsum

                              print(fsum(tup[1] for tup in array) / len(array))






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited yesterday

























                              answered yesterday









                              ruoholaruohola

                              2,016424




                              2,016424













                              • it gives this error : 'int' object is not callable

                                – Şevval Kahraman
                                yesterday











                              • @ŞevvalKahraman it gives no errors for me with your example array, you probably have a typo somewhere.

                                – ruohola
                                yesterday













                              • @ruohola The reason it works for the example is it's 40 / 5 which gives 8 with no remainder. In Python 2, with different numbers, it could truncate the answer.

                                – Peter Wood
                                yesterday











                              • @PeterWood it will not truncate anything if you use the float(len(array)) casting when using Python 2. Anyways it shouldn't even matter since this question was for Python 3.x.

                                – ruohola
                                yesterday













                              • As it's python 3, just use statistics.mean.

                                – Peter Wood
                                yesterday



















                              • it gives this error : 'int' object is not callable

                                – Şevval Kahraman
                                yesterday











                              • @ŞevvalKahraman it gives no errors for me with your example array, you probably have a typo somewhere.

                                – ruohola
                                yesterday













                              • @ruohola The reason it works for the example is it's 40 / 5 which gives 8 with no remainder. In Python 2, with different numbers, it could truncate the answer.

                                – Peter Wood
                                yesterday











                              • @PeterWood it will not truncate anything if you use the float(len(array)) casting when using Python 2. Anyways it shouldn't even matter since this question was for Python 3.x.

                                – ruohola
                                yesterday













                              • As it's python 3, just use statistics.mean.

                                – Peter Wood
                                yesterday

















                              it gives this error : 'int' object is not callable

                              – Şevval Kahraman
                              yesterday





                              it gives this error : 'int' object is not callable

                              – Şevval Kahraman
                              yesterday













                              @ŞevvalKahraman it gives no errors for me with your example array, you probably have a typo somewhere.

                              – ruohola
                              yesterday







                              @ŞevvalKahraman it gives no errors for me with your example array, you probably have a typo somewhere.

                              – ruohola
                              yesterday















                              @ruohola The reason it works for the example is it's 40 / 5 which gives 8 with no remainder. In Python 2, with different numbers, it could truncate the answer.

                              – Peter Wood
                              yesterday





                              @ruohola The reason it works for the example is it's 40 / 5 which gives 8 with no remainder. In Python 2, with different numbers, it could truncate the answer.

                              – Peter Wood
                              yesterday













                              @PeterWood it will not truncate anything if you use the float(len(array)) casting when using Python 2. Anyways it shouldn't even matter since this question was for Python 3.x.

                              – ruohola
                              yesterday







                              @PeterWood it will not truncate anything if you use the float(len(array)) casting when using Python 2. Anyways it shouldn't even matter since this question was for Python 3.x.

                              – ruohola
                              yesterday















                              As it's python 3, just use statistics.mean.

                              – Peter Wood
                              yesterday





                              As it's python 3, just use statistics.mean.

                              – Peter Wood
                              yesterday











                              2














                              If you're open to more golf-like solutions, you can transpose your array with vanilla python, get a list of just the numbers, and calculate the mean with



                              sum(zip(*array)[1])/len(array)





                              share|improve this answer








                              New contributor




                              Nick Amin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                              Check out our Code of Conduct.

























                                2














                                If you're open to more golf-like solutions, you can transpose your array with vanilla python, get a list of just the numbers, and calculate the mean with



                                sum(zip(*array)[1])/len(array)





                                share|improve this answer








                                New contributor




                                Nick Amin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                Check out our Code of Conduct.























                                  2












                                  2








                                  2







                                  If you're open to more golf-like solutions, you can transpose your array with vanilla python, get a list of just the numbers, and calculate the mean with



                                  sum(zip(*array)[1])/len(array)





                                  share|improve this answer








                                  New contributor




                                  Nick Amin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                  Check out our Code of Conduct.










                                  If you're open to more golf-like solutions, you can transpose your array with vanilla python, get a list of just the numbers, and calculate the mean with



                                  sum(zip(*array)[1])/len(array)






                                  share|improve this answer








                                  New contributor




                                  Nick Amin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                  Check out our Code of Conduct.









                                  share|improve this answer



                                  share|improve this answer






                                  New contributor




                                  Nick Amin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                  Check out our Code of Conduct.









                                  answered yesterday









                                  Nick AminNick Amin

                                  211




                                  211




                                  New contributor




                                  Nick Amin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                  Check out our Code of Conduct.





                                  New contributor





                                  Nick Amin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                  Check out our Code of Conduct.






                                  Nick Amin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                  Check out our Code of Conduct.























                                      1














                                      you can use map instead of list comprehension



                                      sum(map(lambda x:int(x[1]), array)) / len(array)


                                      or functools.reduce (if you use Python2.X just reduce not functools.reduce)



                                      import functools
                                      functools.reduce(lambda acc, y: acc + y[1], array, 0) / len(array)





                                      share|improve this answer


























                                      • first one gives this error : 'int' object is not callable

                                        – Şevval Kahraman
                                        yesterday











                                      • @ŞevvalKahraman if array is defined as shown in your question - the first one give 8.0 (tested & verified on same version). So either the array your using has a different value somewhere or you made a typo

                                        – JGreenwell
                                        yesterday











                                      • x[1] is already an integer, why do you need to call int()?

                                        – Barmar
                                        yesterday











                                      • Using a lambda is 30% slower than a generator comprehension. But if you prefer map, I recommend using operator.itemgetter(1) instead of the lambda.

                                        – Mateen Ulhaq
                                        yesterday













                                      • Similarly, functools.reduce is 72% slower than a generator comprehension and sum.

                                        – Mateen Ulhaq
                                        yesterday


















                                      1














                                      you can use map instead of list comprehension



                                      sum(map(lambda x:int(x[1]), array)) / len(array)


                                      or functools.reduce (if you use Python2.X just reduce not functools.reduce)



                                      import functools
                                      functools.reduce(lambda acc, y: acc + y[1], array, 0) / len(array)





                                      share|improve this answer


























                                      • first one gives this error : 'int' object is not callable

                                        – Şevval Kahraman
                                        yesterday











                                      • @ŞevvalKahraman if array is defined as shown in your question - the first one give 8.0 (tested & verified on same version). So either the array your using has a different value somewhere or you made a typo

                                        – JGreenwell
                                        yesterday











                                      • x[1] is already an integer, why do you need to call int()?

                                        – Barmar
                                        yesterday











                                      • Using a lambda is 30% slower than a generator comprehension. But if you prefer map, I recommend using operator.itemgetter(1) instead of the lambda.

                                        – Mateen Ulhaq
                                        yesterday













                                      • Similarly, functools.reduce is 72% slower than a generator comprehension and sum.

                                        – Mateen Ulhaq
                                        yesterday
















                                      1












                                      1








                                      1







                                      you can use map instead of list comprehension



                                      sum(map(lambda x:int(x[1]), array)) / len(array)


                                      or functools.reduce (if you use Python2.X just reduce not functools.reduce)



                                      import functools
                                      functools.reduce(lambda acc, y: acc + y[1], array, 0) / len(array)





                                      share|improve this answer















                                      you can use map instead of list comprehension



                                      sum(map(lambda x:int(x[1]), array)) / len(array)


                                      or functools.reduce (if you use Python2.X just reduce not functools.reduce)



                                      import functools
                                      functools.reduce(lambda acc, y: acc + y[1], array, 0) / len(array)






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited yesterday

























                                      answered yesterday









                                      minjiminji

                                      185110




                                      185110













                                      • first one gives this error : 'int' object is not callable

                                        – Şevval Kahraman
                                        yesterday











                                      • @ŞevvalKahraman if array is defined as shown in your question - the first one give 8.0 (tested & verified on same version). So either the array your using has a different value somewhere or you made a typo

                                        – JGreenwell
                                        yesterday











                                      • x[1] is already an integer, why do you need to call int()?

                                        – Barmar
                                        yesterday











                                      • Using a lambda is 30% slower than a generator comprehension. But if you prefer map, I recommend using operator.itemgetter(1) instead of the lambda.

                                        – Mateen Ulhaq
                                        yesterday













                                      • Similarly, functools.reduce is 72% slower than a generator comprehension and sum.

                                        – Mateen Ulhaq
                                        yesterday





















                                      • first one gives this error : 'int' object is not callable

                                        – Şevval Kahraman
                                        yesterday











                                      • @ŞevvalKahraman if array is defined as shown in your question - the first one give 8.0 (tested & verified on same version). So either the array your using has a different value somewhere or you made a typo

                                        – JGreenwell
                                        yesterday











                                      • x[1] is already an integer, why do you need to call int()?

                                        – Barmar
                                        yesterday











                                      • Using a lambda is 30% slower than a generator comprehension. But if you prefer map, I recommend using operator.itemgetter(1) instead of the lambda.

                                        – Mateen Ulhaq
                                        yesterday













                                      • Similarly, functools.reduce is 72% slower than a generator comprehension and sum.

                                        – Mateen Ulhaq
                                        yesterday



















                                      first one gives this error : 'int' object is not callable

                                      – Şevval Kahraman
                                      yesterday





                                      first one gives this error : 'int' object is not callable

                                      – Şevval Kahraman
                                      yesterday













                                      @ŞevvalKahraman if array is defined as shown in your question - the first one give 8.0 (tested & verified on same version). So either the array your using has a different value somewhere or you made a typo

                                      – JGreenwell
                                      yesterday





                                      @ŞevvalKahraman if array is defined as shown in your question - the first one give 8.0 (tested & verified on same version). So either the array your using has a different value somewhere or you made a typo

                                      – JGreenwell
                                      yesterday













                                      x[1] is already an integer, why do you need to call int()?

                                      – Barmar
                                      yesterday





                                      x[1] is already an integer, why do you need to call int()?

                                      – Barmar
                                      yesterday













                                      Using a lambda is 30% slower than a generator comprehension. But if you prefer map, I recommend using operator.itemgetter(1) instead of the lambda.

                                      – Mateen Ulhaq
                                      yesterday







                                      Using a lambda is 30% slower than a generator comprehension. But if you prefer map, I recommend using operator.itemgetter(1) instead of the lambda.

                                      – Mateen Ulhaq
                                      yesterday















                                      Similarly, functools.reduce is 72% slower than a generator comprehension and sum.

                                      – Mateen Ulhaq
                                      yesterday







                                      Similarly, functools.reduce is 72% slower than a generator comprehension and sum.

                                      – Mateen Ulhaq
                                      yesterday













                                      0














                                      You could use map:



                                      np.mean(list(map(lambda x: x[1], array)))






                                      share|improve this answer




























                                        0














                                        You could use map:



                                        np.mean(list(map(lambda x: x[1], array)))






                                        share|improve this answer


























                                          0












                                          0








                                          0







                                          You could use map:



                                          np.mean(list(map(lambda x: x[1], array)))






                                          share|improve this answer













                                          You could use map:



                                          np.mean(list(map(lambda x: x[1], array)))







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered yesterday









                                          pdpinopdpino

                                          1647




                                          1647























                                              0














                                              Just find the average using sum and number of elements of the list.



                                              array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
                                              avg = float(sum(value[1] for value in array)) / float(len(array))
                                              print(avg)
                                              #8.0





                                              share|improve this answer






























                                                0














                                                Just find the average using sum and number of elements of the list.



                                                array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
                                                avg = float(sum(value[1] for value in array)) / float(len(array))
                                                print(avg)
                                                #8.0





                                                share|improve this answer




























                                                  0












                                                  0








                                                  0







                                                  Just find the average using sum and number of elements of the list.



                                                  array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
                                                  avg = float(sum(value[1] for value in array)) / float(len(array))
                                                  print(avg)
                                                  #8.0





                                                  share|improve this answer















                                                  Just find the average using sum and number of elements of the list.



                                                  array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
                                                  avg = float(sum(value[1] for value in array)) / float(len(array))
                                                  print(avg)
                                                  #8.0






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited yesterday

























                                                  answered yesterday









                                                  Devesh Kumar SinghDevesh Kumar Singh

                                                  4,0351426




                                                  4,0351426























                                                      0














                                                      One way would be to define a structured array from the list of tuples:



                                                      l = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
                                                      a = np.array(l, dtype=([('str', '<U1'), ('num', '<i4')]))


                                                      And then take the np.mean of the numerical field, i.e the second element in the tuples:



                                                      np.mean(a['num'])
                                                      # 8.0





                                                      share|improve this answer






























                                                        0














                                                        One way would be to define a structured array from the list of tuples:



                                                        l = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
                                                        a = np.array(l, dtype=([('str', '<U1'), ('num', '<i4')]))


                                                        And then take the np.mean of the numerical field, i.e the second element in the tuples:



                                                        np.mean(a['num'])
                                                        # 8.0





                                                        share|improve this answer




























                                                          0












                                                          0








                                                          0







                                                          One way would be to define a structured array from the list of tuples:



                                                          l = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
                                                          a = np.array(l, dtype=([('str', '<U1'), ('num', '<i4')]))


                                                          And then take the np.mean of the numerical field, i.e the second element in the tuples:



                                                          np.mean(a['num'])
                                                          # 8.0





                                                          share|improve this answer















                                                          One way would be to define a structured array from the list of tuples:



                                                          l = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]
                                                          a = np.array(l, dtype=([('str', '<U1'), ('num', '<i4')]))


                                                          And then take the np.mean of the numerical field, i.e the second element in the tuples:



                                                          np.mean(a['num'])
                                                          # 8.0






                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited 9 hours ago

























                                                          answered 10 hours ago









                                                          yatuyatu

                                                          17.2k41844




                                                          17.2k41844






























                                                              draft saved

                                                              draft discarded




















































                                                              Thanks for contributing an answer to Stack Overflow!


                                                              • 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%2fstackoverflow.com%2fquestions%2f55843611%2fis-there-any-pythonic-way-to-find-average-of-specific-tuple-elements-in-array%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

                                                              VNC viewer RFB protocol error: bad desktop size 0x0I Cannot Type the Key 'd' (lowercase) in VNC Viewer...

                                                              Couldn't open a raw socket. Error: Permission denied (13) (nmap)Is it possible to run networking commands...

                                                              Why not use the yoke to control yaw, as well as pitch and roll? Announcing the arrival of...