Reputation: 21
import csv
with open('Annual_Budget.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
Column_Sum = []
Third_Column_Avg = []
High_Value = []
Low_Value = []
for row in readCSV:
Column_Sum = []
Third_Column_Avg = []
High_Value = []
Low_Value = []
Column_Sum.append(Column_Sum)
Third_Column_Avg.append(Third_Column_Avg)
High_Value.append(High_Value)
Low_Value.append(Low_Value)
print(Column_Sum)
print(Third_Column_Avg)
print(High_Value)
print(Low_Value)`
How to read a csv as a text file and for each row add up the all of the numeric columns, skipping any columns that cannot be perceived as numbers and displays the sum when it is completed. It must also display the average of all values in the third column. It must also display the highest value and lowest value from the second column and show which row these values appeared in. I put a mock annual budget in picture format so you can get the idea of what I am trying to accomplish.
CSV SCREENSHOT EXAMPLE
Output: [SUM OF ALL NUMERIC COLUMNS], [AVERAGE OF ALL VALUES IN THIRD COLUMN], [HIGHEST VALUE FROM SECOND COLUMN][LOWEST VALUE FROM SECOND COLUMN]
Upvotes: 2
Views: 60
Reputation: 764
With the pandas library (I made a file just like your screenshot) if you don't have this library just pip install pandas
then
In [1]: import pandas as pd
In [2]: my_file = pd.read_csv('stack.csv')
In [3]: my_file
Out[3]:
anual budget q2 q4
0 100 450 20
1 600 765 50
2 500 380 79
3 800 480 455
4 1100 65 4320
Anual budget, q2 and q4 sum
my_file['anual budget '].sum()
my_file['q2'].sum()
my_file['q4'].sum()
Average of third column
my_file['q4'].mean()
Min and max value of second column
my_file['q2'].max()
my_file['q2'].min()
Upvotes: 2