Question

In: Computer Science

Python I am creating a program that allows a user to extract data from a .csv...

Python

I am creating a program that allows a user to extract data from a .csv file and print the statistics of a certain column in that file. The statistics include Count, Mean, Standard Deviation, Min, and Max. Here is the code I have so far:

import csv
import json

class POP:
""" Extract the data """
def __init__(self, line):
self.data = line
# get elements
self.id = self.data[0].strip()
self.geography = self.data[1].strip()
self.targetGeoId = self.data[2].strip()
self.targetGeoId2 = self.data[3].strip()
self.popApr1 = self.data[4].strip()
self.popJul1 = self.data[5].strip()
self.changePop = self.data[6].strip()

population = list()
with open('PopChange.csv', 'r') as p:
reader = csv.reader(p)
next(reader)
for line in reader:
population.append(POP(line))
population.append(POP(line))

obj = POP(line)
print(obj.popApr1)

As seen above, I am trying to print out the Count, Mean, Standard Deviation, Min, and Max of the column "popApr1", which is a column in the file. When I tried to print using print(obj.popApr1), it did not work. I believe that this action can be done using the .describe() method, but I am unsure of the syntax.

Solutions

Expert Solution

Solution:

  1. import the statistics module
  2. read the CSV file
  3. create POP objects for each line
  4. place the obj.popApr1 value from each line in a list
  5. use python standard library method len(), min(), max() to get count, min and max for the list created above
  6. use statistics module's method mean() and stdev to get the value of mean and standard deviation for the list created above

Code (PLEASE REFER THE SCREENNSHOT FOR INDENTATION OF THE PYTHON SCRIPT):

import csv
""" import statistics module to calculate mean and standard deviation """
import statistics

class POP:
""" Extract the data """
def __init__(self, line):
self.data = line
# get elements
self.id = self.data[0].strip()
self.geography = self.data[1].strip()
self.targetGeoId = self.data[2].strip()
self.targetGeoId2 = self.data[3].strip()
self.popApr1 = self.data[4].strip()
self.popJul1 = self.data[5].strip()
self.changePop = self.data[6].strip()

population = []
""" list to store popApr1 column value """
popApr1List = []
with open('PopChange.csv', 'r') as p:
reader = csv.reader(p)
next(reader)
for line in reader:
population.append(POP(line))
population.append(POP(line))

obj = POP(line)
""" append the value of obj.popApr1 to list """
popApr1List.append(float(obj.popApr1))

""" print count by getting length of list """
print ("Count: ", len(popApr1List))

""" print mean using statistics module's mean method """
print ("Mean: ", statistics.mean(popApr1List))

""" print min and max using python standard library methods """
print("Max: ", max(popApr1List))
print("Min: ", min(popApr1List))

""" print standard deviation using statistics module's stdev method """
print("Standard Deviation: ", statistics.stdev(popApr1List))

Input file used for testing:

Output:


Related Solutions

I am creating a program in Python that allows the user to input a credit card...
I am creating a program in Python that allows the user to input a credit card number, and determine if the card is valid. This should be done by taking every other number, starting from the right, and adding them together. The doubling each of the other digits, and adding them together as single digits, and then adding the two sums together. For example, if the number 4833 1200 3412 3456 is used, the first sum should be 6+4+2+4+0+2+3+8=29, the...
Python I am creating a class in python. Here is my code below: import csv import...
Python I am creating a class in python. Here is my code below: import csv import json population = list() with open('PopChange.csv', 'r') as p: reader = csv.reader(p) next(reader) for line in reader: population.append(obj.POP(line)) population.append(obj.POP(line)) class POP: """ Extract the data """ def __init__(self, line): self.data = line # get elements self.id = self.data[0].strip() self.geography = self.data[1].strip() self.targetGeoId = self.data[2].strip() self.targetGeoId2 = self.data[3].strip() self.popApr1 = self.data[4].strip() self.popJul1 = self.data[5].strip() self.changePop = self.data[6].strip() The problem is, I get an error saying:  ...
I am creating a crop watering "simulator" in Python. I have the user input an array...
I am creating a crop watering "simulator" in Python. I have the user input an array and then must compare the placement of water and crops to determine if all the crops in the array are watered. The user will either input a "w" for water or "c" for crop when creating the array. A w cell can water 8 cells around it, including itself. My end result must determine if all the crops will be watered or not. How...
I am trying to create a program that reads from a csv file and finds the...
I am trying to create a program that reads from a csv file and finds the sum of total volume in liters of liquor sold from the csv file by county and print that list out by county in descending order. Currently my program runs and gives me the right answers but it is not in descending order. I tried this:     for county, volume in sorted(sums_by_volume.items(), key=lambda x: x[1], reverse=True):         index +=1         print("{}. {} {:.2f}".format(county, sums_by_volume[county]))      When I run...
Create a Python program that: Allows the user to enter a phrase or sentence. The program...
Create a Python program that: Allows the user to enter a phrase or sentence. The program should then take the phrase or sentence entered Separate out the individual words entered Each individual word should then be added to a list After all of the words have been place in a list Sort the contents of the list Display the contents of the sorted list with each individual word displayed on a separate line Display a message to the user indicating...
I am having a trouble with a python program. I am to create a program that...
I am having a trouble with a python program. I am to create a program that calculates the estimated hours and mintutes. Here is my code. #!/usr/bin/env python3 #Arrival Date/Time Estimator # # from datetime import datetime import locale mph = 0 miles = 0 def get_departure_time():     while True:         date_str = input("Estimated time of departure (HH:MM AM/PM): ")         try:             depart_time = datetime.strptime(date_str, "%H:%M %p")         except ValueError:             print("Invalid date format. Try again.")             continue        ...
How to do this in Python (using Lists): Create a python program that allows a user...
How to do this in Python (using Lists): Create a python program that allows a user to display, sort and update as needed a List of U.S States containing the State Capital and State Bird. You will need to embed the State data into your Python code. The user interface will allow the user to perform the following functions: 1. Display all U.S. States in Alphabetical order along with Capital and Bird 2. Search for a specific state and display...
Use Visual Python or equivalent, to write a program that allows the user to observe the...
Use Visual Python or equivalent, to write a program that allows the user to observe the following: Damped and forced harmonic oscillators. The program should be user friendly and have default values for the initial velocities, positions, masses, and spring constants as well as damping constants. Values and frequencies for the forced oscillators should also be given. It should allow the user to input values for the velocities, positions, spring constants, and masses. The program should determine automatically the scale...
9) This is in Python Code a program that allows the user to manage its expenses...
9) This is in Python Code a program that allows the user to manage its expenses accepting the following commands: - Add <player_name> -> This command adds a new player to the system. Assume there can’t be repeated names. If a name already exists then an error is shown to the user. - Score <player_name> <score> -> This command adds the score to the player with the name player-name. Each score needs to be added individually - Report -> This...
Write in Python and as 2 seperate programs Write a program that allows the user to...
Write in Python and as 2 seperate programs Write a program that allows the user to enter the total rainfall for each of 12 months into a LIST. The program should calculate and display the total rainfall for the year, the average monthly rainfall, and the months with the highest and lowest rainfall amounts. Data: January 7.9 inches February 10.1 inches March 3.4 inches April 6.7 inches May 8.9 inches June 9.4 inches July 5.9 inches August 4.1 inches September...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT