For a homework assignment we had to write a couple python scripts. The first analyzes monthly financial data to find the average monthly change, and the min and max changes along with their corresponding month. The second one can be used to count votes for an election and determine the winner. Both scripts output to a text file. The second one uses Pandas Data Frames. Both written using python 3. These and more are available on my github:
https://github.com/bendgame
Find Monthly Change:
import csv import os #fetch the file file = os.path.join ('..', 'PyBank','PyBank_data.csv') #create placeholder lists for the data months = [] net_total = [] with open (file, newline = "") as csvfile: readcsv = csv.reader(csvfile, delimiter = ',') csv_header = next(csvfile) #put the data into lists for row in readcsv: months.append(row[0]) net_total.append(int(row[1])) #count the number of months month_count = len(months) #set variables for loops x = 1 y = 0 #average change place holder average_change = (net_total[1]-net_total[0]) #place holder list for changes changes = [] #for loop to calculate month to month change and dump the values into a list for month in range(month_count-1): average_change = (net_total[x] - net_total[y]) changes.append(int(average_change)) x+=1 y+=1 #Calcuate the average monthly change and round it av_mon_chng = round(sum(changes)/(month_count -1),2) #find the min and max change min_change = min(changes) max_change = max(changes) #return the index to find the positions in the list chng_i_min = changes.index(min_change) chng_i_max = changes.index(max_change) #find the months for the min and max changes min_chng_month = months[chng_i_min + 1] max_chng_month = months[chng_i_max + 1] #Print the values in console print("Financial Analysis") print("----------------------------") print(f"Months: {len(months)}") print(f"Total: ${sum(net_total)}") print(f"Average Monthly Change: {av_mon_chng}") print(f"Greatest Increase in Profits: {max_chng_month} (${max_change})") print(f"Greatest Decrease in Profits: {min_chng_month} (${min_change})") #Write the output to a text file fin_analysis = open("Financial_Analysis.txt","w") fin_analysis.write("Financial Analysis\n") fin_analysis.write("----------------------------\n") fin_analysis.write(f"Months: {len(months)}\n") fin_analysis.write(f"Total: ${sum(net_total)}\n") fin_analysis.write(f"Average Monthly Change: {av_mon_chng}\n") fin_analysis.write(f"Greatest Increase in Profits: {max_chng_month} (${max_change})\n") fin_analysis.write(f"Greatest Decrease in Profits: {min_chng_month} (${min_change})\n") fin_analysis.close()
Count votes and determine a winner:
import pandas as pd import os # Make a reference to the csv file path csvfile = os.path.join ('..', 'PyPoll','election_data.csv') # read the csv file as a DataFrame elec_data = pd.read_csv(csvfile) df_ed = pd.DataFrame(elec_data) #create an empty list to store vote counts as percent percent_count = [] #Create a list of unique(distinct) candidates candidates = list(df_ed["Candidate"].unique()) #count the number of times the candidate appears and put into a list counts = list(df_ed['Candidate'].value_counts()) #get the total vote count total_votes = sum(counts) #set variable for for loop x = 0 #for loop to calculate percentages for candidate in candidates: percentage = round(counts[x]/total_votes,3) percentage="{:.3%}".format(percentage) percent_count.append(percentage) x+=1 #create a zipped list of data to rebuild data frame data = list(zip(candidates, percent_count, counts)) #calculate counts to find winner max_count = df_ed['Candidate'].value_counts() #find the most counts winner_count = max_count.max() #put the zipped data into a data frame df_data = pd.DataFrame(data) #search the data frame for the candidate with the most counts put it into a list winner = list(df_data.loc[df_data[2]== winner_count,0]) #rename the columns for df_data sorted_data =df_data.columns =["Candidate |", "Percent of Votes |", "Vote Count"] #sort the columns by vote count in descending order for clean output sorted_data = df_data.sort_values("Vote Count", ascending = False ) #print the output into console print("Election Results") print(" -------------------------") print(f"Total Votes: {total_votes}") print("--------------------------") print(f"{sorted_data}") print(f" -------------------------") print(f"Winner: {winner}") print(f"-------------------------") #Write the outcome data to a txt file named election_winner election_winner = open("election_winner.txt","w") election_winner.write("Election Results\n") election_winner.write("----------------------------\n") election_winner.write(f"Total Votes: {total_votes}\n") election_winner.write(f"--------------------------\n") election_winner.write(f"{sorted_data}\n") election_winner.write(f" -------------------------\n") election_winner.write(f"Winner: {winner}\n") election_winner.write(f"-------------------------") election_winner.close()