forked from udacity/pdsnd_github
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbikeshare.py
235 lines (184 loc) · 9.23 KB
/
bikeshare.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
MONTH_DATA = ['all', 'january', 'february', 'march', 'april', 'may', 'june']
DAY_DATA = ['all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
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
"""
print('Hello! Let\'s explore some US bikeshare data!')
# TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
city_name = ''
while city_name.lower() not in CITY_DATA:
city_name = input("\nWhich city would you like to analyze? (E.g. Input either chicago, new york city, washington)\n")
if city_name.lower() in CITY_DATA:
#We were able to get the name of the city to analyze data.
city = CITY_DATA[city_name.lower()]
else:
#We were not able to get the name of the city to analyze data so we continue the loop.
print("Sorry, that city was not recognized. Please input either chicago, new york city or washington.\n")
# TO DO: get user input for month (all, january, february, ... , june)
month_name = ''
while month_name.lower() not in MONTH_DATA:
month_name = input("\nWhat is the name of the month to filter data? (E.g. Input either 'all' to apply no month filter or january, february, ... , june)\n")
if month_name.lower() in MONTH_DATA:
#We were able to get the name of the month to analyze data.
month = month_name.lower()
else:
#We were not able to get the name of the month to analyze data so we continue the loop.
print("Sorry, that month was not recognized. Please input either 'all' to apply no month filter or january, february, ... , june.\n")
# TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
day_name = ''
while day_name.lower() not in DAY_DATA:
day_name = input("\nWhat is the name of the day to filter data? (E.g. Input either 'all' to apply no day filter or monday, tuesday, ... sunday)\n")
if day_name.lower() in DAY_DATA:
#We were able to get the name of the month to analyze data.
day = day_name.lower()
else:
#We were not able to get the name of the month to analyze data so we continue the loop.
print("Sorry we were not able to get the name of the day to filter data, Please input either 'all' to apply no day filter or monday, tuesday, ... sunday.\n")
print('-'*40)
return city, month, day
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
"""
# load data file into a dataframe
df = pd.read_csv(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
df['hour'] = df['Start Time'].dt.hour
# filter by month if applicable
if month != 'all':
# use the index of the months list to get the corresponding int
month = MONTH_DATA.index(month)
# 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 time_stats(df):
"""Displays statistics on the most frequent times of travel.
Args:
(DataFrame) df - Pandas DataFrame containing city data filtered by month and day
"""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# TO DO: display the most common month
common_month = df['month'].mode()[0]
print("The most common month from the given fitered data is: " + MONTH_DATA[common_month].title())
# TO DO: display the most common day of week
common_day_of_week = df['day_of_week'].mode()[0]
print("The most common day of week from the given fitered data is: " + common_day_of_week)
# TO DO: display the most common start hour
common_start_hour = df['hour'].mode()[0]
print("The most common start hour from the given fitered data is: " + str(common_start_hour))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip.
Args:
(DataFrame) df - Pandas DataFrame containing city data filtered by month and day
"""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# TO DO: display most commonly used start station
common_start_station = df['Start Station'].mode()[0]
print("The most commonly used start station from the given fitered data is: " + common_start_station)
# TO DO: display most commonly used end station
common_end_station = df['End Station'].mode()[0]
print("The most commonly used end station from the given fitered data is: " + common_end_station)
# TO DO: display most frequent combination of start station and end station trip
frequent_combination = (df['Start Station'] + "||" + df['End Station']).mode()[0]
print("The most frequent combination of start station and end station trip is : " + str(frequent_combination.split("||")))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration.
Args:
(DataFrame) df - Pandas DataFrame containing city data filtered by month and day
"""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# TO DO: display total travel time
total_travel_time = df['Trip Duration'].sum()
print("The total travel time from the given fitered data is: " + str(total_travel_time))
# TO DO: display mean travel time
mean_travel_time = df['Trip Duration'].mean()
print("The mean travel time from the given fitered data is: " + str(mean_travel_time))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df, city):
"""Displays statistics on bikeshare users.
Args:
(DataFrame) df - Pandas DataFrame containing city data filtered by month and day
"""
print('\nCalculating User Stats...\n')
start_time = time.time()
# TO DO: Display counts of user types
user_types = df['User Type'].value_counts()
print("The count of user types from the given fitered data is: \n" + str(user_types))
if city == 'chicago.csv' or city == 'new_york_city.csv':
# TO DO: Display counts of gender
gender = df['Gender'].value_counts()
print("The count of user gender from the given fitered data is: \n" + str(gender))
# TO DO: Display earliest, most recent, and most common year of birth
earliest_birth = df['Birth Year'].min()
most_recent_birth = df['Birth Year'].max()
most_common_birth = df['Birth Year'].mode()[0]
print('Earliest birth from the given fitered data is: {}\n'.format(earliest_birth))
print('Most recent birth from the given fitered data is: {}\n'.format(most_recent_birth))
print('Most common birth from the given fitered data is: {}\n'.format(most_common_birth) )
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def display_raw_data(df):
"""Displays raw data on user request.
Args:
(DataFrame) df - Pandas DataFrame containing city data filtered by month and day
"""
print(df.head())
next = 0
while True:
view_raw_data = input('\nWould you like to view next five row of raw data? Enter yes or no.\n')
if view_raw_data.lower() != 'yes':
return
next = next + 5
print(df.iloc[next:next+5])
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df, city)
while True:
view_raw_data = input('\nWould you like to view first five row of raw data? Enter yes or no.\n')
if view_raw_data.lower() != 'yes':
break
display_raw_data(df)
break
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()