<file_sep># Python-CSV Data Analysis

Using python scripting to data mine two different CSV datasets and extract the useful data.

## PyBank
Analyze the dataset for a company budget (budget_data.csv) to discover:

  * The total number of months included in the dataset
  * The total net amount of "Profit/Losses" over the entire period
  * The average change in "Profit/Losses" between months over the entire period
  * The greatest increase in profits (date and amount) over the entire period
  * The greatest decrease in losses (date and amount) over the entire period
  
 ![Financial Analysis](PC_Images/Financial_Analysis_Results.png)
  

## Pypoll
Use Python scripting to speed up the counting of the [election_data](PyPoll/Resources/election_data.csv) from a small town by calculating each of the following:

  * The total number of votes cast

  * A complete list of candidates who received votes

  * The percentage of votes each candidate won

  * The total number of votes each candidate won

  * The winner of the election based on popular vote.
  
 
![Vote Count](PC_Images/PyPoll_Results.png)
<file_sep># Import dependencies and open file path
import os
import csv
file = os.path.join("PyBank","Resources", "budget_data.csv") 


with open(file, newline="") as csvfile:              
    csvreader = csv.reader(csvfile, delimiter=",")
    next(csvreader)
    
    
    # Create variables to hold values.
    total_rev=0             
    prior_month_rev=0       
    total_monthly_change=0  
    max_monthly_rev_inc=0   
    max_monthly_rev_dec=0   
    
    
    # Loop throught each row/line of data in the input file (budget_csv).
    for row in csvreader:
        date = row[0]
        total_rev += float(row[1])
    # Calculate monthly revenue change. 
        # Skip first month since no previous month data.
        if csvreader.line_num == 2:
            monthly_change = 0
        else:
            monthly_change = float(row[1])-prior_month_rev
        # Add monthly_change to total.
        total_monthly_change += monthly_change  
        # While looping, find the greatest revenue increase/decrease
        if monthly_change > max_monthly_rev_inc:
            max_monthly_rev_inc = monthly_change
            date_max_rev_inc = date
        elif monthly_change < max_monthly_rev_dec:
            max_monthly_rev_dec = monthly_change
            date_max_rev_dec = date
        # Update the prior month revenue variable.
        prior_month_rev = float(row[1])
        
    #Count up total months
    total_months = int(csvreader.line_num-1) 
    
    #Print results
    print("Financial Analysis")
    print("----------------------------")
    print("Total Months: " + str(total_months))
    # In calculations and print statements below, various numeric values are cast to int in order to print a whole number
    print("Total Revenue: $" + str(int(total_rev))) 
    print("Average Revenue Change $" + str(int(total_monthly_change/total_months)))
    print("Greatest Increase in Revenue: " + date_max_rev_inc + " ($" +
           str(int(max_monthly_rev_inc))+")")
    print("Greatest Decrease in Revenue: " + date_max_rev_dec + " ($" +
           str(int(max_monthly_rev_dec)) + ")" )

# Export a text file with the same results.
text_file = os.path.join("instructions","PyBank",'Resources', 'Financial_Analysis_1.txt')
with open(text_file, 'w') as f:
    f.write("Financial Analysis\n")
    f.write("----------------------------\n")
    f.write("Total Months: " + str(total_months) + "\n")
    f.write("Average Revenue Change $" + str(int(total_monthly_change/total_months)) + "\n")
    f.write("Greatest Increase in Revenue: " + date_max_rev_inc + " ($" +
           str(int(max_monthly_rev_inc)) + ")" + "\n")
    f.write("Greatest Decrease in Revenue: " + date_max_rev_dec + " ($" +
            str(int(max_monthly_rev_dec)) + ")" + "\n")<file_sep>#Import dependencies
import os
import csv



#Create variables
poll = {}
total_votes = 0
candidates = []
num_votes = []
vote_percent = []
winner_list = []

# Open and read csv file.
file = os.path.join("PyPoll","Resources", "election_data.csv")


with open(file, 'r') as csvfile:
    csvread = csv.reader(csvfile)
    next(csvread, None)


# Loops through rows, use column 3 as keys. Count votes for each candidate.
    for row in csvread:
        total_votes += 1
        if row[2] in poll.keys():
            poll[row[2]] = poll[row[2]] + 1
        else:
            poll[row[2]] = 1
 


for key, value in poll.items():
    candidates.append(key)
    num_votes.append(value)


# Calculate percentage of votes each candidate won.
for n in num_votes:
    vote_percent.append(round(n/total_votes*100, 1))


# Zip candidates, num_votes, vote_percent into tuples.
clean_data = list(zip(candidates, num_votes, vote_percent))


# Calculate and declare winner.
for name in clean_data:
    if max(num_votes) == name[1]:
        winner_list.append(name[0])
winner = winner_list[0]


# In the event of a tie, print both names. 
if len(winner_list) > 1:
    for w in range(1, len(winner_list)):
        winner = winner + " tied with " + winner_list[w]


# Create outputs text file
text_file = os.path.join('Output', 'election_results_' + str(file_num) +'.txt')

with open(text_file, 'w') as txtfile:
    txtfile.writelines('Election Results \n------------------------- \nTotal Votes: ' + str(total_votes) + 
      '\n-------------------------\n')
    for entry in clean_data:
        txtfile.writelines(entry[0] + ": " + str(entry[2]) +'%  (' + str(entry[1]) + ')\n')
    txtfile.writelines('------------------------- \nWinner: ' + winner + '\n-------------------------')

# Print file to terminal
with open(output_file, 'r') as readfile:
    print(readfile.read())