Is there any pythonic way to find average of specific tuple elements in array? Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!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?

Passing args from the bash script to the function in the script

Multiple options vs single option UI

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

Do I need to protect SFP ports and optics from dust/contaminants? If so, how?

Why doesn't the standard consider a template constructor as a copy constructor?

What’s with the clanks at the end of the credits in Avengers: Endgame?

"Rubric" as meaning "signature" or "personal mark" -- is this accepted usage?

c++ diamond problem - How to call base method only once

Was Dennis Ritchie being too modest in this quote about C and Pascal?

Is it possible to cast 2x Final Payment while sacrificing just one creature?

Bayes factor vs P value

Contradiction proof for inequality of P and NP?

Is it acceptable to use working hours to read general interest books?

Can you stand up from being prone using Skirmisher outside of your turn?

iOS App Store: Unable to download and update apps due to Terms and Conditions loop, even after agreeing

Would reducing the reference voltage of an ADC have any effect on accuracy?

What is /etc/mtab in Linux?

What to do with someone that cheated their way through university and a PhD program?

My bank got bought out, am I now going to have to start filing tax returns in a different state?

Are these square matrices always diagonalisable?

Scheduling based problem

I preordered a game on my Xbox while on the home screen of my friend's account. Which of us owns the game?

Does Feeblemind produce an ongoing magical effect that can be dispelled?

First instead of 1 when referencing



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



Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar Manara
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!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;








9















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
    3 hours ago






  • 1





    @PeterWood python 3.7

    – Şevval Kahraman
    2 hours ago

















9















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
    3 hours ago






  • 1





    @PeterWood python 3.7

    – Şevval Kahraman
    2 hours ago













9












9








9








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 2 hours ago









ruohola

1,894420




1,894420










asked 4 hours ago









Şevval KahramanŞevval Kahraman

845




845












  • What version of Python are you using?

    – Peter Wood
    3 hours ago






  • 1





    @PeterWood python 3.7

    – Şevval Kahraman
    2 hours ago

















  • What version of Python are you using?

    – Peter Wood
    3 hours ago






  • 1





    @PeterWood python 3.7

    – Şevval Kahraman
    2 hours ago
















What version of Python are you using?

– Peter Wood
3 hours ago





What version of Python are you using?

– Peter Wood
3 hours ago




1




1





@PeterWood python 3.7

– Şevval Kahraman
2 hours ago





@PeterWood python 3.7

– Şevval Kahraman
2 hours ago












7 Answers
7






active

oldest

votes


















9














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)


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 loop over the values in the array into a comprehension expression, 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
    3 hours ago






  • 1





    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
    2 hours ago












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

    – Peter Wood
    1 hour ago


















1














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
































    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
      3 hours ago


















    1














    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
      3 hours ago











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

      – ruohola
      2 hours ago












    • @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
      2 hours ago











    • @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
      2 hours ago



















    1














    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
































      0














      You could use map:



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






      share|improve this answer























      • works, thanks a lot

        – Şevval Kahraman
        3 hours ago


















      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

























      • Fixed it, Thank you for the suggestion @PeterWood

        – Devesh Kumar Singh
        3 hours ago











      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

























      7 Answers
      7






      active

      oldest

      votes








      7 Answers
      7






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      9














      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)


      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 loop over the values in the array into a comprehension expression, 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
        3 hours ago






      • 1





        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
        2 hours ago












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

        – Peter Wood
        1 hour ago















      9














      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)


      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 loop over the values in the array into a comprehension expression, 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
        3 hours ago






      • 1





        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
        2 hours ago












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

        – Peter Wood
        1 hour ago













      9












      9








      9







      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)


      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 loop over the values in the array into a comprehension expression, 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)


      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 loop over the values in the array into a comprehension expression, 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 2 hours ago

























      answered 3 hours ago









      Peter WoodPeter Wood

      16.8k33876




      16.8k33876












      • 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
        3 hours ago






      • 1





        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
        2 hours ago












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

        – Peter Wood
        1 hour ago

















      • 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
        3 hours ago






      • 1





        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
        2 hours ago












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

        – Peter Wood
        1 hour ago
















      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
      3 hours ago





      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
      3 hours ago




      1




      1





      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
      2 hours ago






      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
      2 hours ago














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

      – Peter Wood
      1 hour ago





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

      – Peter Wood
      1 hour ago













      1














      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





























        1














        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



























          1












          1








          1







          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 3 hours ago

























          answered 3 hours ago









          gmdsgmds

          8,060932




          8,060932





















              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
                3 hours ago















              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
                3 hours ago













              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 3 hours ago

























              answered 3 hours ago









              minjiminji

              167110




              167110












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

                – Şevval Kahraman
                3 hours ago

















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

                – Şevval Kahraman
                3 hours ago
















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

              – Şevval Kahraman
              3 hours ago





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

              – Şevval Kahraman
              3 hours ago











              1














              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
                3 hours ago











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

                – ruohola
                2 hours ago












              • @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
                2 hours ago











              • @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
                2 hours ago
















              1














              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
                3 hours ago











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

                – ruohola
                2 hours ago












              • @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
                2 hours ago











              • @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
                2 hours ago














              1












              1








              1







              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 1 hour ago

























              answered 4 hours ago









              ruoholaruohola

              1,894420




              1,894420












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

                – Şevval Kahraman
                3 hours ago











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

                – ruohola
                2 hours ago












              • @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
                2 hours ago











              • @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
                2 hours ago


















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

                – Şevval Kahraman
                3 hours ago











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

                – ruohola
                2 hours ago












              • @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
                2 hours ago











              • @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
                2 hours ago

















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

              – Şevval Kahraman
              3 hours ago





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

              – Şevval Kahraman
              3 hours ago













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

              – ruohola
              2 hours ago






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

              – ruohola
              2 hours ago














              @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
              2 hours ago





              @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
              2 hours ago













              @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
              2 hours ago






              @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
              2 hours ago












              1














              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





























                1














                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



























                  1












                  1








                  1







                  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 46 mins ago

























                  answered 1 hour ago









                  GraipherGraipher

                  4,6891634




                  4,6891634





















                      0














                      You could use map:



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






                      share|improve this answer























                      • works, thanks a lot

                        – Şevval Kahraman
                        3 hours ago















                      0














                      You could use map:



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






                      share|improve this answer























                      • works, thanks a lot

                        – Şevval Kahraman
                        3 hours ago













                      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 3 hours ago









                      pdpinopdpino

                      1647




                      1647












                      • works, thanks a lot

                        – Şevval Kahraman
                        3 hours ago

















                      • works, thanks a lot

                        – Şevval Kahraman
                        3 hours ago
















                      works, thanks a lot

                      – Şevval Kahraman
                      3 hours ago





                      works, thanks a lot

                      – Şevval Kahraman
                      3 hours ago











                      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

























                      • Fixed it, Thank you for the suggestion @PeterWood

                        – Devesh Kumar Singh
                        3 hours ago















                      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

























                      • Fixed it, Thank you for the suggestion @PeterWood

                        – Devesh Kumar Singh
                        3 hours ago













                      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 3 hours ago

























                      answered 3 hours ago









                      Devesh Kumar SinghDevesh Kumar Singh

                      3,4421425




                      3,4421425












                      • Fixed it, Thank you for the suggestion @PeterWood

                        – Devesh Kumar Singh
                        3 hours ago

















                      • Fixed it, Thank you for the suggestion @PeterWood

                        – Devesh Kumar Singh
                        3 hours ago
















                      Fixed it, Thank you for the suggestion @PeterWood

                      – Devesh Kumar Singh
                      3 hours ago





                      Fixed it, Thank you for the suggestion @PeterWood

                      – Devesh Kumar Singh
                      3 hours ago

















                      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

                      Oświęcim Innehåll Historia | Källor | Externa länkar | Navigeringsmeny50°2′18″N 19°13′17″Ö / 50.03833°N 19.22139°Ö / 50.03833; 19.2213950°2′18″N 19°13′17″Ö / 50.03833°N 19.22139°Ö / 50.03833; 19.221393089658Nordisk familjebok, AuschwitzInsidan tro och existensJewish Community i OświęcimAuschwitz Jewish Center: MuseumAuschwitz Jewish Center

                      Valle di Casies Indice Geografia fisica | Origini del nome | Storia | Società | Amministrazione | Sport | Note | Bibliografia | Voci correlate | Altri progetti | Collegamenti esterni | Menu di navigazione46°46′N 12°11′E / 46.766667°N 12.183333°E46.766667; 12.183333 (Valle di Casies)46°46′N 12°11′E / 46.766667°N 12.183333°E46.766667; 12.183333 (Valle di Casies)Sito istituzionaleAstat Censimento della popolazione 2011 - Determinazione della consistenza dei tre gruppi linguistici della Provincia Autonoma di Bolzano-Alto Adige - giugno 2012Numeri e fattiValle di CasiesDato IstatTabella dei gradi/giorno dei Comuni italiani raggruppati per Regione e Provincia26 agosto 1993, n. 412Heraldry of the World: GsiesStatistiche I.StatValCasies.comWikimedia CommonsWikimedia CommonsValle di CasiesSito ufficialeValle di CasiesMM14870458910042978-6

                      Typsetting diagram chases (with TikZ?) Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)How to define the default vertical distance between nodes?Draw edge on arcNumerical conditional within tikz keys?TikZ: Drawing an arc from an intersection to an intersectionDrawing rectilinear curves in Tikz, aka an Etch-a-Sketch drawingLine up nested tikz enviroments or how to get rid of themHow to place nodes in an absolute coordinate system in tikzCommutative diagram with curve connecting between nodesTikz with standalone: pinning tikz coordinates to page cmDrawing a Decision Diagram with Tikz and layout manager