def station_stats(df): """Displays statistics on the most popular stations and trip.""" clear() print('Calculating the Most Popular Stations and Trip...') start_time = time.time() # Calc the "most common" station stats most_common_start = df['Start Station'].mode()[0] most_common_end = df['End Station'].mode()[0] most_common_trip = df.groupby(['Start Station', 'End Station']).size() \ .sort_values(ascending=False) \ .reset_index(name='count') # Print calculation performance times print('This operation took {} seconds to complete.'.format(time.time() - start_time)) print('-' * 40) # Display the station statistics print('Most common start station: {0}\n'.format(most_common_start) + 'Most common end station: {0}\n'.format(most_common_end) + 'Most common trip: {0} to {1}\n'.format( most_common_trip['Start Station'][0], most_common_trip['End Station'][0])) input('Press [enter] to return to Main Menu...')
def user_stats(city, df): """Displays statistics on bikeshare users.""" clear() print('Calculating User Stats...') start_time = time.time() # Calc the user stats output = '' failed_gender = False failed_birth_year = False user_count = df.groupby('User Type').size().reset_index(name='count') try: gender_count = df.groupby('Gender').size().reset_index(name='count') except KeyError: failed_gender = True try: min_birth_year = df['Birth Year'].min() max_birth_year = df['Birth Year'].max() most_common_birth_year = df['Birth Year'].mode()[0] except KeyError: failed_birth_year = True # Print calculation performance times print('This operation took {} seconds to complete.'.format(time.time() - start_time)) print('-' * 40) # Build output string by combining literals and looping through dataframes output += 'Counts of User Types\n\n' for i, row in user_count.iterrows(): output += (str(row[0]) + ":" + ' ' * (20 - len(str(row[0]) + str(row[1]))) + str(row[1]) + '\n') output += '\nCounts of Genders\n\n' if not failed_gender: for i, row in gender_count.iterrows(): output += (str(row[0]) + ":" + ' ' * (20 - len(str(row[0]) + str(row[1]))) + str(row[1]) + '\n') else: output += 'No Gender data found for ' + city.title() + '.\n' output += '\nBirth Year Statistics\n\n' if not failed_birth_year: output += ('Earliest birth year: ' + str(min_birth_year)[:4] + '\n' + 'Most recent birth year: ' + str(max_birth_year)[:4] + '\n' + 'Most common birth year: ' + str(most_common_birth_year)[:4] + '\n') else: output += 'No Birth Year data found for ' + city.title() + '.\n' print(output) input('Press [enter] to return to Main Menu...')
def menu(city, month, day, df): """ Presents the user with navigation options to each of the stat groupings and the setting screen. Collects the correspdoning user choice and calls the appropriate function. """ # Initialize variables choice = '' options = { '1': time_stats, '2': station_stats, '3': trip_duration_stats, '4': user_stats, '5': disp_raw_data, '6': None, 'q': None } #Loop menu until user quits while choice != 'q': # Reinitialize choice choice = '' # Clear the screen clear() # Print main menu options print('Main Menu\n' + '-' * 40) print('City: ' + city.title()) print('Month: ' + month.title()) print('Day: ' + day.title() + '\n' + '-' * 40) print('Navigation Options:\n' + '1. Time Statistics\n' + '2. Station Statistics\n' + '3. Trip Duration Statistics\n' + '4. User Statistics\n' + '5. Raw Data\n' + '6. Settings\n' + 'Q. Quit\n') while choice not in options: choice = input("Where would you like to go? ").lower() if choice not in options: print('Invalid choice. Please try again.') if choice not in ['4', '6', 'q']: options[choice](df) elif choice == '4': options[choice](city, df) elif choice == '6': city, month, day = get_filters() df = load_data(city, month, day)
def add_entry(): name = input('Enter name:') clear() task = input('Enter task name:') clear() while (True): str_time = input('Enter number of minutes spent on the task:') clear() try: int_time = int(str_time) break except ValueError: print('Cannot be converted to number. Please try again.') continue clear() notes = input('Enter any additional notes:') clear() database.add_entry(name=name, time=int_time, task=task, notes=notes) return 'Entry successfully added to the database'
def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ # Clear the screen and display loading message clear() print("Loading data set based on selected conditions...") # Load the appropriate csv based on city provided by user df = pd.read_csv(CITY_DATA[city]) # Convert the Start Time column to datetime df['Start Time'] = pd.to_datetime(df['Start Time']) # Extract month and day of week from Start Time to create new columns df['month'] = df['Start Time'].dt.month df['day_of_week'] = df['Start Time'].dt.weekday_name # Filter by month if applicable if month != 'all': # Use the index of the months list to get the corresponding int months = ['january', 'february', 'march', 'april', 'may', 'june'] month = months.index(month.lower()) + 1 # Filter by month to create the new dataframe df = df.loc[df['month'] == month] # Filter by day of week if applicable if day != 'all': # Filter by day of week to create the new dataframe df = df.loc[df['day_of_week'] == day.title()] return df
def menu(): database.init_db() while True: clear() print('WORK LOG') print('What whould you like to do?') while True: answer = input(('1: Add new entry\n' '2: Search in existing entries\n' '3: Quit Program\n')) if answer in '123': break else: clear() print( f'Option {answer} is not in the menu. Please choose again.' ) continue clear() if answer == '1': input(work_log.add_entry()) if answer == '2': search_option = work_log.search_entries() if search_option == '1': work_log.display_entries(work_log.find_by_employee()) if search_option == '2': work_log.display_entries(work_log.find_by_date()) if search_option == '3': work_log.display_entries(work_log.find_by_time_spent()) if search_option == '4': work_log.display_entries(work_log.find_by_search_term()) if answer == '3': print('Thank you for using work log.') input() break
def time_stats(df): """Displays statistics on the most frequent times of travel.""" clear() print('Calculating the Most Frequent Times of Travel...') start_time = time.time() # Calc the "most common" time stats most_common_month = df['month'].mode()[0] most_common_day = df['day_of_week'].mode()[0] most_common_hour = df['Start Time'].dt.hour.mode()[0] # Print calculation performance times print('This operation took {} seconds to complete.'.format(time.time() - start_time)) print('-' * 40) # Display the statistics print('Most common month: {0}\n'.format(most_common_month) + 'Most common day of week: {0}\n'.format(most_common_day) + 'Most common hour: {0}\n'.format(most_common_hour)) input('Press [enter] to return to Main Menu...')
def display_entries(entries): list_entries = list() if entries: for entry in entries: list_entries.append(entry) index = 0 while (True): while (True): clear() if (len(list_entries) == 0): print('No result found') input() return print(f'Result: {index + 1} of {len(list_entries)}\n') print_entry(list_entries[index]) print('\n') if len(list_entries) == 1: choice = input('[B]ack\n') elif index == 0: choice = input('[N]ext, [B]ack\n') elif len(list_entries) - 1 == index: choice = input('[P]revious, [B]ack\n') else: choice = input('[P]revious, [N]ext, [B]ack\n') choice = choice.upper() if choice in 'PNB': break else: continue if choice == 'N' and index < len(list_entries) - 1: index = index + 1 if choice == 'P' and index > 0: index = index - 1 if choice == 'B': break
def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" clear() print('Calculating the total and average Trip Duration...') start_time = time.time() # Calc the total and average trip duration total_trip_duration = df['Trip Duration'].sum() mean_trip_duration = df['Trip Duration'].mean() # Print calculation performance times print('This operation took {} seconds to complete.'.format(time.time() - start_time)) print('-' * 40) # Display trip duration statistics print( 'Total trip duration: {0} days, {1} hours, {2} minutes, and {3} seconds\n' .format(*convert_seconds(total_trip_duration)) + 'Average (mean) trip duration: {0} days, {1} hours, {2} minutes, and {3} seconds\n' .format(*convert_seconds(mean_trip_duration))) input('Press [enter] to return to Main Menu...')
def find_by_time_spent(): clear() while (True): str_time = input('Enter number of minutes spent on the task:') clear() try: int_time = int(str_time) break except ValueError: print('Cannot be converted to number. Please try again.') continue clear() entries = database.search_by_time(int_time) return entries
def search_entries(): clear() print('Choose search option:') while True: answer = input('1: Find by employee \n' + '2: Find by date \n' + '3: Find by minutes spents \n' + '4: Find by search term \n') if answer in '1234': break else: clear() print(f'Option {answer} is not in the menu. Please choose again.') continue clear() return answer
def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ city = "" month = "" day = "" months = ['january', 'february', 'march', 'april', 'may', 'june', 'all'] days_of_week = [ 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'all' ] # Clear the screen clear() # Get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs while city not in CITY_DATA: city = input( "Please select a city's data to analyze (\"Chicago\", \"New York City\", or \"Washington\"): " ).lower() if city not in CITY_DATA: print("Invalid selection.") # Get user input for month (all, january, february, ... , june) clear() print('City: ' + city.title() + '\n' + '-' * 40) while month not in months: month = input( "If you'd like to filter the data by a specific month, \n" + "enter that month's name here (January - June). Otherwise, enter \"all\": " ).lower() if month not in months: print("Invalid selection.") # Get user input for day of week (all, monday, tuesday, ... sunday) clear() print('City: ' + city.title()) print('Month: ' + month.title() + '\n' + '-' * 40) while day not in days_of_week: day = input( "If you'd like to filter the data by a specific day of the week, \n" + "enter that day's name here (Monday - Friday). Otherwise, enter \"all\": " ).lower() if day not in days_of_week: print("Invalid selection.") clear() print('City: ' + city.title()) print('Month: ' + month.title()) print('Day: ' + day.title() + '\n' + '-' * 40) choice = input("Do the above settings look correct (no to reselect)? ") if choice.lower() == "no": city, month, day = get_filters() return city, month, day
def find_by_employee(): clear() print('Search by:') while True: answer = input('1: list of all employee entries \n' + '2: writing the name of an employee \n') if answer in '12': break else: clear() print(f'Option {answer} is not in the menu. Please choose again.') continue clear() if answer == '1': unique_employees = database.Entry.select( database.Entry.name).distinct() options = '' employees = list() for count, emp in enumerate(unique_employees, 1): employees.append(emp.name) options += f'{count}: {emp.name}\n' while True: print('Choose the employee:') answer = input(options) try: option = int(answer) if option > len(employees): raise ValueError except ValueError: clear() print( f'Option {answer} is not in the menu. Please choose again.' ) continue break clear() entries = database.Entry.select().where( database.Entry.name == employees[option - 1]) return entries if answer == '2': search_term = input('Please enter name of the employee: ') # seach for all the unique employees unique_employees = database.Entry.select(database.Entry.name).where( database.Entry.name.contains(search_term)).distinct() options = '' employees = list() # make list of unique employees for count, emp in enumerate(unique_employees, 1): employees.append(emp.name) options += f'{count}: {emp.name}\n' while True: if len(employees) == 1: option = 1 break clear() print('Choose the employee:') answer = input(options) try: option = int(answer) if option > len(employees): raise ValueError except ValueError: clear() print( f'Option {answer} is not in the menu. Please choose again') continue break entries = database.search_by_name(employees[option - 1]) return entries
def find_by_search_term(): clear() search_term = input('Enter the search term (task or notes): ') entries = database.search_by_string(search_term) return entries
def find_by_date(): while True: answer = input('1: find by list of dates \n' + '2: find by listing range of dates \n') if answer in '12': break else: clear() print(f'Option {answer} is not in the menu. Please choose again.') continue if answer == '1': clear() unique_dates = database.Entry.select(database.Entry.date).distinct() options = '' dates = list() # list of dates to choose from for count, date in enumerate(unique_dates, 1): dates.append(date.date) options += f'{count}: {date.date}\n' while True: print('Choose the Date:') answer = input(options) try: option = int(answer) if option > len(dates): raise ValueError except ValueError: clear() print( f'Option {answer} is not in the menu. Please choose again') continue break option = option - 1 entries = database.search_by_range(dates[option], dates[option]) clear() return entries if answer == '2': clear() while True: try: print('Enter the date range') date1 = input('Please use DD/MM/YYYY date #1: ') valid_date1 = datetime.datetime.strptime(date1, '%d/%m/%Y') date2 = input('Please use DD/MM/YYYY date #2: ') valid_date2 = datetime.datetime.strptime(date2, '%d/%m/%Y') break except ValueError: print('One of the date are not a valid date') input('Press enter to try again') clear() continue entries = database.search_by_range(valid_date1, valid_date2) return entries
def welcome_message(): """Prints a welcome message""" clear() print('Hello! Let\'s explore some US bikeshare data!') input('Press [enter] to continue...')
def quit_message(): """Prints a message on screen as user leaves program""" clear() print('Goodbye.') time.sleep(1.0) clear()