Question

23.4 PROJECT 4: Using Pandas for data analysis and practice with error handling Overview In this...

23.4 PROJECT 4: Using Pandas for data analysis and practice with error handling

Overview

In this project, you will use the Pandas module to analyze some data about some 20th century car models, country of origin, miles per gallon, model year, etc.

Provided Input Files

An input file with nearly 200 rows of data about automobiles. The input file has the following format (the same as what you had for your chapter 13 labs). The following is an example of some of the lines in the file:

mpg,cylinders,displacement,horsepower,weight,acceleration,model_year,origin,name
18,8,307,130,3504,12,70,usa,chevrolet chevelle malibu
15,8,350,165,3693,11.5,70,usa,buick skylark 320
18,8,318,150,3436,11,70,usa,plymouth satellite
16,8,304,150,3433,12,70,usa,amc rebel sst

Description

The first thing your program will need to do is prompt the user for a csv file name. Your prompt must be exactly Enter the filename:You will then read that csv file into a dataframe, and use that data in your analysis. If the file can not be opened, your program should not crash, but should print out the message Can't open file. Exiting program. and then exit the program.

You will use a menu, like in the last project, and call several functions according to the user's menu selection.

You program should have a menu exactly as follows (the menu always prints a blank line first):

(1) Get max mpg model
(2) Get min mpg model
(3) Get model year range
(4) Exit

Enter selection 1-4:

If the user enters an invalid menu selection (including a non-numeric input, or a number outside of the valid range), your program should not crash, but should print the message Invalid selection - must be a number from 1 to 4, then display the menu again. For each menu selection other than Exit, you will first prompt the user for a country of origin. The prompt should be exactly Enter the country of origin: (with a space following the colon). The countries that are in the file are "usa", "japan", and "europe". Then you will call a function for each menu selection and country that was input. If the user enters an unexpected input for the country, you should output the message Invalid country and then display the entire menu again, including the beginning blank line (you do not need to remember which menu item they selected).

An example of what output should look like for a sample of various inputs follows this description.

You will need to use the following functions:

  • def get_max_mpg_model(carsdataframe, country) - this function will accept as parameters a dataframe of data, with the same columns as the original file, and a country, which is a string. The function should return a string which is the name of the car model from the country indicated that has the maximum mpg of all models from that country. For example, if the user selected menu item 1 and then input 'usa', the get_max_mpg_model function will be passed a data frame and the string 'usa'. It will return the string 'chevrolet chevette', since the chevrolet chevette is the model name with the best mpg among those models in the data whose country of origin is the usa. Upon return from the function with the above parameters, the following message should be printed: Best mpg model from usa is chevrolet chevette

  • def get_min_mpg_model(carsdataframe, country) - this function is the same as the get_max_mpg_model function, but will return the model name with the minimum mpg for the indicated country. The message printed upon return from the function would be something like Worst mpg model from usa is chevrolet chevette

  • def get_model_year_range(carsdataframe, country) - this function will take as parameters a dataframe and a country, like the other two, but this function will return two values, the minimum model year and the maximum model year for the indicated country. The message printed upon return from this function is, as an example Model years range from 1970 to 1975. Note that when the data is read into the data frame, the years are two digit integers. You will have to change them to strings in order to output the correct message.

  • Your code will be cleaner and much easier if you create a function that prints the menu.

In the main program, you should open the input file using the pandas read_csv() method and read the contents of the file into a DataFrame. Then display the menu to see what the user wants to do, and perform the function as indicated by the user.

Once the selected menu function has returned, the main program should print out the best (max) mpg model, the worst (min) mpg model, or the model year range according to the selected function, as follows:

Example: If the user inputs the following, in order:

mpg.csv
1
usa
3
japan
2
europe
4

the console will look like this:

Enter the filename:mpg.csv

(1) Get max mpg model
(2) Get min mpg model
(3) Get model year range
(4) Exit

Enter selection 1-4:1

Enter the country of origin: usa
Best mpg model from usa is: chevrolet chevette

(1) Get max mpg model
(2) Get min mpg model
(3) Get model year range
(4) Exit

Enter selection 1-4:3

Enter the country of origin: japan
Model years range from 1970 to 1975

(1) Get max mpg model
(2) Get min mpg model
(3) Get model year range
(4) Exit

Enter selection 1-4:2

Enter the country of origin: europe
Worst mpg model from europe is: volvo 145e (sw)

(1) Get max mpg model
(2) Get min mpg model
(3) Get model year range
(4) Exit

Enter selection 1-4:4

If the user inputs a bogus file name, the output should look like this:

Enter the filename:bogusfilename
Can't open file.  Exiting program.

If the user inputs an invalid menu choice, like -3 or end, the output should look like this:

Enter the filename:mpg.csv

(1) Get max mpg model
(2) Get min mpg model
(3) Get model year range
(4) Exit

Enter selection 1-4:-3
Invalid selection - must be a number from 1 to 4

(1) Get max mpg model
(2) Get min mpg model
(3) Get model year range
(4) Exit

Enter selection 1-4:end
Invalid selection - must be a number from 1 to 4

(1) Get max mpg model
(2) Get min mpg model
(3) Get model year range
(4) Exit

Enter selection 1-4:4

If the user inputs an invalid country, such as australia, the output should look like this:

Enter the filename:mpg.csv

(1) Get max mpg model
(2) Get min mpg model
(3) Get model year range
(4) Exit

Enter selection 1-4:1

Enter the country of origin: australia
Invalid country

(1) Get max mpg model
(2) Get min mpg model
(3) Get model year range
(4) Exit

Enter selection 1-4:4

NOTE: The interactive terminal in zyBooks does NOT work with data frames. This means you MUST use Spyder or some other environment to develop your project, then once it is working, you can paste it into zyBooks for testing. Remember that your output and your prompts need to be EXACTLY as shown in the specifications in order to pass the tests.

Second Note: mpg.csv is available to download. If you pass the first test, but can not pass the other ones, it is likely because you hard coded something about the data from the mpg.csv file. Your program needs to work no matter what other file is tested. You will not be able to see the other test file. If your program is working properly for the mpg.csv file, it will work properly for the other file as well.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

ANSWER:

Below i am providing the screen shots to this code along with output.

In get_max_mpg_model i have used a for loop with a condition to copy all mpg values of a particular country.

and in get_model_year_rang i am returning a tuple value which is unwrapped in calling function.

Editor - C:\Users\sookshmas\Desktop\sample_projects cars.py cars.py 1 import pandas as pd 3 def unique(listi): # intilize a ncars.py ® print((4) Exit\n\n\n) print(Enter selection 1-4: ) try: choice-int(input()) if choice==4: break except ValueErr1 mpg, cylinders, displacement, horsepower, weight, acceleration, model year, origin, name 2 18,8,307,130,3504,12, 2001, usa,IPython console a Console 1/A Python 3.7.5 (default, Oct 31 2019, 15:18:51) [MSC v.1916 64 bit (AMD64)] Type copyright, crIPython console Console 1/A (1) Get max mpg model (2) Get min mpg model (3) Get model year range (4) Exit Enter selection 1-4IPython console Console 1/ usa Model years range from 2001 to 2012 (1) Get max mpg model (2) Get min mpg model (3) Get modelIPython console Console 1/ usa Model years range from 2001 to 2012 (1) Get max mpg model (2) Get min mpg model (3) Get modelIPython console Console 1/13 Enter the country of origin: germany Invalid country (1) Get max mpg model (2) Get min mpg model

This is the complete code for this project please refer the above screenshots for indentation.

import pandas as pd

def unique(list1):
  
# intilize a null list
unique_list = []
  
# traverse for all elements
for x in list1:
# check if exists in unique_list or not
if x not in unique_list:
unique_list.append(x)
return unique_list
def get_max_mpg_model(carsdataframe, country):
res=[carsdataframe["mpg"][idx] for idx,t in enumerate(carsdataframe["origin"]) if t == country]
  
return max(res)
  
  
def get_min_mpg_model(carsdataframe, country):
res=[carsdataframe["mpg"][idx] for idx,t in enumerate(carsdataframe["origin"]) if t == country]
return min(res)
  
def get_model_yrar_range(carsdataframe,country):
res=[carsdataframe["model_year"][idx] for idx,t in enumerate(carsdataframe["origin"]) if t == country]
return (min(res),max(res))

def main():
print("Enter the filename: ")
filename=input()
try:
carsdata=pd.read_csv(filename)
countries=unique(carsdata["origin"])
choice=0
while(choice!=4):
print("(1) Get max mpg model\n")
print("(2) Get min mpg model\n")
print("(3) Get model year range\n")
print("(4) Exit\n\n\n")
print("Enter selection 1-4: ")
try:
choice=int(input())
if choice==4:
break
except ValueError:
print("Invalid selection - must be a number from 1 to 4\n")
choice=0
continue
  
if choice!=0:
print("\nEnter the country of origin: " )
c=input()
if not c in countries:
print("\n Invalid country\n")
choice=0
if choice==0:
pass
elif choice==1:
res=get_max_mpg_model(carsdata,c)
print("\nBest mpg model from "+str(c)+" is: "+str(res)+" \n")
elif choice==2:
res=get_min_mpg_model(carsdata,c)
print("\nWorst mpg model from "+str(c)+" is: "+str(res)+" \n")
elif choice==3:
fr,to=get_model_yrar_range(carsdata,c)
print("\nModel years range from "+str(fr)+" to "+str(to)+" \n")
elif choice > 4:
print("Invalid selection - must be a number from 1 to 4\n")
choice=0
except OSError as e:
print(e)
print("CAn't open file. Exiting program")
  
if _name_ =="_main_":
main()

Add a comment
Know the answer?
Add Answer to:
23.4 PROJECT 4: Using Pandas for data analysis and practice with error handling Overview In this...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 23.4 Project 4: Using Pandas for data analysis and practice with error handling Python Please! 23.4...

    23.4 Project 4: Using Pandas for data analysis and practice with error handling Python Please! 23.4 PROJECT 4: Using Pandas for data analysis and practice with error handling Overview In this project, you will use the Pandas module to analyze some data about some 20th century car models, country of origin, miles per gallon, model year, etc. Provided Input Files An input file with nearly 200 rows of data about automobiles. The input file has the following format (the same...

  • 22.39 LAB 13 C FALL 2019 Overview Demonstrate your ability to use pandas with functions Description...

    22.39 LAB 13 C FALL 2019 Overview Demonstrate your ability to use pandas with functions Description Write a program that reads data from an input file using a DataFrame and displays a subset of data using a method Provided Input Files An input file with nearly 200 rows of data about automobiles. The input file has the following format: mpg, cylinders, displacement, horsepower, weight, acceleration, model_year, origin, name 18,9,307,130,3504, 12, 70, usa, chevrolet chevelle malibu 15,8,350,165,3693, 11.5,70, usa, buick skylark...

  • Lab Exercise #15 Assignment Overview This lab exercise provides practice with Pandas data analysis library. Data...

    Lab Exercise #15 Assignment Overview This lab exercise provides practice with Pandas data analysis library. Data Files We provide three comma-separated-value file, scores.csv , college_scorecard.csv, and mpg.csv. The first file is list of a few students and their exam grades. The second file includes data from 1996 through 2016 for all undergraduate degree-granting institutions of higher education. The data about the institution will help the students to make decision about the institution for their higher education such as student completion,...

  • In this project, you will use functions and dictionaries to track basketball players and their respective...

    In this project, you will use functions and dictionaries to track basketball players and their respective points, then display statistics of points made. You will need three functions as follows: def freeThrowMade(playerDictionary, playerName) - this function will add 1 point to the player's total score def twoPointMade(playerDictionary, playerName) - this function will add 2 points to the player's total score def threePointMade(playerDictionary, playerName) - this function will add 3 points to the player's total score Each of these functions has...

  • This is a quick little assignment I have to do, but I missed alot of class...

    This is a quick little assignment I have to do, but I missed alot of class due to the Hurricane and no one here knows what theyre doing. please help! this is Java with intelli-J Overview In this project students will build a four-function one-run calculator on the command line. The program will first prompt the user for two numbers, then display a menu with five operations. It will allow the user to select an option by reading input using...

  • Please make a JAVA program for the following using switch structures Write a program that simulates...

    Please make a JAVA program for the following using switch structures Write a program that simulates a simple Calculator program. The program will display menu choices to the user to Add, Subtract, Multiply and Divide. The program will prompt the user to make a selection from the choices and get their choice into the program. The program will use a nested if….else (selection control structure) to determine the user’s menu choice. Prompt the user to enter two numbers, perform the...

  • Java Data Structures

    Programming Instructions:Using      Java Object Oriented Principles, write a program which produces the      code as indicated in the following specifications: Your       program must be a console application that provides a user this exact       menu:Please select one of the following:1: Add Client to Bank2: Display Clients in the Bank3: Set Bank Name4: Search for a Client5: Exit Enter your Selection: <keyboard input here> The       menu must be displayed repeatedly until 5...

  • Methods: Net beans IDE Java two methods. Identifier: calculateScore(String word) Parameters: word – the word for...

    Methods: Net beans IDE Java two methods. Identifier: calculateScore(String word) Parameters: word – the word for which you should calculate the points in Scrabble Return Value: int – the number of points for the parameter word Other: This method should be static. This method should use the following system for scoring: 0 – blank 1 – e, a, i, o, n, r, t, l, s, u 2 – d, g 3 – b, c, m, p 4 – f, h,...

  • The purpose of this assignment is to get experience with an array, do while loop and...

    The purpose of this assignment is to get experience with an array, do while loop and read and write file operations. Your goal is to create a program that reads the exam.txt file with 10 scores. After that, the user can select from a 4 choice menu that handles the user’s choices as described in the details below. The program should display the menu until the user selects the menu option quit. The project requirements: It is an important part...

  • Menu-driven programs will display the menu options to the user and then prompt them for a...

    Menu-driven programs will display the menu options to the user and then prompt them for a menu choice. This program will display the following menu in the following format: Calculator Options: Calculate the area of a circle Calculate the area of a rectangle Calculate the area of a triangle Calculate the area of a trapezoid Calculate the area of a sphere Exit Enter your choice (1-6) Once the user enters a choice for the menu, the program should use a...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT