Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem with Generator
#5
You can use the module statistics.

Buran's code extended.
Instead of list comprehension you should use a for-loop.
The cause is, that you can't catch Exceptions inside a list comprehension.
In the case if one value is not an integer, you get nothing back.

With pandas this should be easier, but I don't use it.


import csv
import statistics


def get_raisedAmt(file, round):
    """
    Generator which yields the column 'raisedAmt'
    from selected round.
    """
    with open(file) as fd:
        rdr = csv.DictReader(fd)
        # each iteration of DictReader
        # yields an dictionary
        # the column header is parsed automatically
        for item in rdr:
            if item["round"] == round:
                try:
                    value = int(item["raisedAmt"])
                except ValueError:
                    continue
                else:
                    yield value


# If you want to reuse the yielded values,
# use tuple, list or other Type you want
my_raised_amt = list(get_raisedAmt("techcruncher.csv", "a"))


# If you know before, that you don't need the original values
# you let statistics.mean or statistics.median consume the generator
# If you have many rows, this saves a lot of memory
my_mean = statistics.mean(get_raisedAmt("techcruncher.csv", "a"))
print("my_mean:", my_mean)

# Now a little bit statistics
mean = statistics.mean(my_raised_amt)
median = statistics.median(my_raised_amt)
print("Mean:", mean)
print("Median:", median)

# there is also a faster method: statistics.fmean
fmean = statistics.fmean(my_raised_amt)
print("fmean:", fmean)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
Problem with Generator - by palladium - Feb-11-2020, 03:46 AM
RE: Problem with Generator - by buran - Feb-11-2020, 04:48 AM
RE: Problem with Generator - by palladium - Feb-13-2020, 02:37 AM
RE: Problem with Generator - by buran - Feb-13-2020, 09:16 AM
RE: Problem with Generator - by DeaD_EyE - Feb-13-2020, 01:26 PM
RE: Problem with Generator - by palladium - Feb-16-2020, 02:20 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  problem in using generator akbarza 2 692 Nov-07-2023, 08:40 AM
Last Post: perfringo
  list call problem in generator function using iteration and recursive calls postta 1 2,013 Oct-24-2020, 09:33 PM
Last Post: bowlofred
  receive from a generator, send to a generator Skaperen 9 5,695 Feb-05-2018, 06:26 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020