how to get the sum of a CSV column list to print
Figured it out, finally. Created two new variables. Renamed totals = []
to totals1 = []
. Then turned the ints in totals 1
into floats using totals2 = [float(integral) for integral in totals1]
, which was used to get the sum with totals3 = sum(totals2)
. New code:
totals1 = [] for row in data:
values = row[1]
totals1.append(values)
totals2 = [float(integral) for integral in totals1] #turns values in totals1 into floats
totals3 = sum(totals2)
How do I SUM a column in a list?
From the documentation:
"Each row read from the csv file is returned as a list of strings"
So your code should be:
sum = 0
with open("cars.csv") as f:
for row in csv.reader(f):
sum += int(row[2])
return sum
Sum a csv column in python
The csv
module loops over your rows one by one, there is no need to then loop over the column. Just sum int(row[1])
:
with open("file.csv") as fin:
headerline = fin.next()
total = 0
for row in csv.reader(fin):
total += int(row[1])
print total
You can use a shortcut with a generator expression and the sum()
built-in function:
with open("file.csv") as fin:
fin.next()
total = sum(int(r[1]) for r in csv.reader(fin))
Note that in Python, strings are sequences too, so when you do for col in row[1]:
you are looping over the individual characters of row[1]
; so for your first row that'd be 1
and 2
:
>>> for c in '123':
... print repr(c)
...
'1'
'2'
'3'
How to find the sum of a column from a csv file using vanilla python (without using numpy or pandas)?
Try doing this -
my_list = [row[-1] for row in read_csv]
print(sum([float(i) for i in my_list[1:]]))
Summing a column in a .csv file using python
Easiest way is to use pandas library.
Use pip install pandas
to install pandas on your machine
and then
import pandas as pd
df = pd.read_csv('your_filename.csv')
sumcol = df['Profit/Losses'].sum()
print(sumcol)
The sum is in sumcol object now. For future reference, If your task is to work with the data provided in csv file, pandas is a blessing. This library provides you with thousands of different types of operations you could perform on your data. Refer Pandas Website for more info.
If you want to make use of csv package only then you can read the csv as a dict and then sum the Profit/Loss entry of dict for each row
total = 0
with open('your_filename.csv', newline='') as csvfile:
data = csv.DictReader(csvfile)
for row in data:
total = total + int(row['Profit/Losses'])
print(total)
Or If you want to use reader instead of dict reader, you need to ignore first row. Something like this
total = 0
with open('your_filename.csv', newline='') as csvfile:
data = csv.reader(csvfile)
for row in data:
if not str(row[1]).startswith('P'):
total = total + int(row[1])
print(total)
Related Topics
How to Select the Last Column of Dataframe
Reading a CSV File into Pandas Dataframe With Quotation in Some Entries
How to Write List Elements into a Tab-Separated File
How to Convert a 1 Channel Image into a 3 Channel With Opencv2
How to Add Multiple Embed Images in an Email Using Python
How to Remove the Double Quote When the Value Is Empty in Spark
Convert CSV to Parquet File Using Python
Tkinter: How to Use Threads to Preventing Main Event Loop from "Freezing"
Django: Check Whether an Object Already Exists Before Adding
Convert Commas Decimal Separators to Dots Within a Dataframe
How to Remove/Delete a Virtualenv
How to Determine Whether a Pandas Column Contains a Particular Value
How to Download the Latest File of an S3 Bucket Using Boto3
In Python, How to Split a String and Keep the Separators