Search code examples
python-3.xcsvsumrow

How to sum values from a row, or a column from a csv file?


Could someone help me out to understand how python sum values from a row and also from a column, the second I believe that I have figured out still I have not grasp the concept so far, once I will be able to assign values, sum, filter to a variable I can move forward to visualisation.

Like sum the 1948 row and so on File Year Jan Fev Mar ... Annual 1948 4.0 4.7 4.5 ... 3.8
1949 5.0 5.8 5.6 ... 5.9 ...

with open('unemployment1948.csv', 'r') as unFile:
        unReader = csv.DictReader(unFile, delimiter = ',')
        unHeads = unReader.fieldnames
        print(unHeads)

        u = defaultdict(float)
        for r in unReader:
            for v in r['Year']:
                try:
                    d[r['1948']] += float(v)
                except ValueError:
                    pass
        print(d)

Solution

  • pandas seems to be the 'go to' tool for work like this in Python.

    Looks like you have a DataFrame so with pandas you should be able to do something like:

    df.sum(axis = 0)
    

    where axis=0 will return values for months and

    df.sum(axis = 1)
    

    will return values for the years.

    This answer also has some examples as well as the pandas docs themselves.