Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

fine_per_plates() Starting in 2004 Michigan moved to issuing plates with the format of ABC1234. That got me thinking, how many vanity plate holders there are

fine_per_plates()

Starting in 2004 Michigan moved to issuing plates with the format of ABC1234. That got me thinking, how many vanity plate holders there are in our dataset? Count the number of Michigan vehicles with plates in the following formats that have received a ticket:

  • ABC1234
  • ABC123
  • 123ABC
  • Vanity Plates (i.e. anything other than the aforementioned formats, including missing or NaN values)

Complete the function fine_per_plates() returning a dictionary. The dictinary should be formatted as follows:

plates_dict = {"ABC1234":the_number_of_vehicles,                "ABC123":the_number_of_vehicles,                "123ABC":the_number_of_vehicles,                "vanity":the_number_of_vehicles}

 

 

 

This is my code: import pandas as pd
import re

def fine_per_plates():
   # Load the ticket data from 'random_ticket_data'
   df = pd.read_csv('random_ticket_data.csv')

   # Define regular expressions for different plate formats
   abc1234_regex = r'^[A-Z]{3}\d{4}$'
   abc123_regex = r'^[A-Z]{3}\d{3}$'
   m123abc_regex = r'^\d{3}[A-Z]{3}$'

   # Create a new column 'plate_format' to store the plate format for each ticket
   df['plate_format'] = df['Plate'].apply(lambda x: 'vanity' if not re.match(abc1234_regex, x) and not re.match(abc123_regex, x) and not re.match(m123abc_regex, x) else x)

   # Initialize a dictionary to store the counts
   plates_dict = {}

   # Loop through each plate format
   for plate_format in ['ABC1234', 'ABC123', '123ABC', 'vanity']:
       # Define the corresponding regex pattern for the plate format
       plate_regex = abc1234_regex if plate_format == 'ABC1234' else abc123_regex if plate_format == 'ABC123' else m123abc_regex if plate_format == '123ABC' else r'^((?!(ABC1234|ABC123|123ABC)).)*$'
       
       # Count the number of vehicles with the specified plate format
       plate_count = len(df[df['plate_format'].str.match(plate_regex)])

       # Calculate the average fine for the specified plate format
       plate_fine = df[df['plate_format'].str.match(plate_regex)]['Fine'].mean()

       # Store the count and average fine in the plates_dict
       plates_dict[plate_format] = {'the_number_of_vehicles': plate_count, 'the_average_fine': plate_fine}

   # Return the dictionary with counts and average fines
   return plates_dict

# Call the function and store the results in a variable
results = fine_per_plates()

# Print the results
print(results)

 

 

this is the output : FileNotFoundError                         Traceback (most recent call last) Cell In[57], line 37     34     return plates_dict     36 # Call the function and store the results in a variable ---> 37 results = fine_per_plates()     39 # Print the results     40 print(results) Cell In[57], line 6, in fine_per_plates()      4 def fine_per_plates():      5     # Load the ticket data from 'random_ticket_data' ----> 6     df = pd.read_csv('random_ticket_data.csv')      8     # Define regular expressions for different plate formats      9     abc1234_regex = r'^[A-Z]{3}\d{4}$' File /opt/conda/lib/python3.9/site-packages/pandas/util/_decorators.py:211, in deprecate_kwarg.._deprecate_kwarg..wrapper(*args, **kwargs)    209     else:    210         kwargs[new_arg_name] = new_arg_value --> 211 return func(*args, **kwargs) File /opt/conda/lib/python3.9/site-packages/pandas/util/_decorators.py:317, in deprecate_nonkeyword_arguments..decorate..wrapper(*args, **kwargs)    311 if len(args) > num_allow_args:    312     warnings.warn(    313         msg.format(arguments=arguments),    314         FutureWarning,    315         stacklevel=find_stack_level(inspect.currentframe()),    316     ) --> 317 return func(*args, **kwargs) File /opt/conda/lib/python3.9/site-packages/pandas/io/parsers/readers.py:950, in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, error_bad_lines, warn_bad_lines, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options)    935 kwds_defaults = _refine_defaults_read(    936     dialect,    937     delimiter,   (...)    946     defaults={"delimiter": ","},    947 )    948 kwds.update(kwds_defaults) --> 950 return _read(filepath_or_buffer, kwds) File /opt/conda/lib/python3.9/site-packages/pandas/io/parsers/readers.py:605, in _read(filepath_or_buffer, kwds)    602 _validate_names(kwds.get("names", None))    604 # Create the parser. --> 605 parser = TextFileReader(filepath_or_buffer, **kwds)    607 if chunksize or iterator:    608     return parser File /opt/conda/lib/python3.9/site-packages/pandas/io/parsers/readers.py:1442, in TextFileReader.__init__(self, f, engine, **kwds)   1439     self.options["has_index_names"] = kwds["has_index_names"]   1441 self.handles: IOHandles | None = None -> 1442 self._engine = self._make_engine(f, self.engine) File /opt/conda/lib/python3.9/site-packages/pandas/io/parsers/readers.py:1729, in TextFileReader._make_engine(self, f, engine)   1727     is_text = False   1728     mode = "rb" -> 1729 self.handles = get_handle(   1730     f,   1731     mode,   1732     encoding=self.options.get("encoding", None),   1733     compression=self.options.get("compression", None),   1734     memory_map=self.options.get("memory_map", False),   1735     is_text=is_text,   1736     errors=self.options.get("encoding_errors", "strict"),   1737     storage_options=self.options.get("storage_options", None),   1738 )   1739 assert self.handles is not None   1740 f = self.handles.handle File /opt/conda/lib/python3.9/site-packages/pandas/io/common.py:857, in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options)    852 elif isinstance(handle, str):    853     # Check whether the filename is to be opened in binary mode.    854     # Binary mode does not support 'encoding' and 'newline'.    855     if ioargs.encoding and "b" not in ioargs.mode:    856         # Encoding --> 857         handle = open(    858             handle,    859             ioargs.mode,    860             encoding=ioargs.encoding,    861             errors=errors,    862             newline="",    863         )    864     else:    865         # Binary mode    866         handle = open(handle, ioargs.mode) FileNotFoundError: [Errno 2] No such file or directory: 'random_ticket_data.csv'

Step by Step Solution

There are 3 Steps involved in it

Step: 1

The error message indicates that the file randomticketda... blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Microeconomics An Intuitive Approach with Calculus

Authors: Thomas Nechyba

1st edition

538453257, 978-0538453257

More Books

Students also viewed these Algorithms questions

Question

Explain the importance of opportunity costs for decision-making.

Answered: 1 week ago

Question

What is the relationship between negative thinking and depression?

Answered: 1 week ago