You can use the module
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.
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!
All humans together. We don't need politicians!