Add all values in a CSV column in Python

后端 未结 4 1214
不知归路
不知归路 2021-01-19 23:11

These seems like something very simple, but search as I might I just can\'t get past it.

I have a CSV file like this:

Day,Event,Value
1,\"Rent\",500
         


        
相关标签:
4条回答
  • 2021-01-19 23:42
    cr = csv.reader(open("file.csv","rb"))
    cr.next() # to skip the header 
    
    total = 0
    for row in cr:  
       total += int(row[2])
       # possibly do other things with data/rows 
    
    print total
    

    There are more terse ways (e.g., list comprehension, or generator expressions) to do this, but this provides the basic idea and also lets you do other things with each line as needed (as pointed out by @MarkRansom too)

    0 讨论(0)
  • 2021-01-19 23:43

    Make a garbage value and read in the first 2 values and "trash" them then when reading in the 3rd value add it to your sum. Don't forget that initially you need to ignore the first 3 values of the file since it will pick up the headers.

    0 讨论(0)
  • 2021-01-19 23:47

    Considering the first line of csv file is 'Day,Event,Value', you can use a generator expression with sum()

    >>> cr = csv.reader(open("file.csv","rb"))
    >>> cr.next()
    >>> print sum(int(x[2]) for x in cr)
    1500
    
    0 讨论(0)
  • 2021-01-19 23:55

    Given that 'value' is in column 2, you can perform the following simple for loop:

    value_sum=0
    for row in cr:
        value_sum += row[2]
    

    Or, you can use a comprehension, if you understand it:

    value_sum = sum([row[2] for row in cr])
    
    0 讨论(0)
提交回复
热议问题