forked from udacity/pdsnd_github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbikeshare.py
More file actions
291 lines (219 loc) · 8.77 KB
/
bikeshare.py
File metadata and controls
291 lines (219 loc) · 8.77 KB
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import time
import pandas as pd
CITY_DATA = {'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv'}
MONTHS = ['january', 'february', 'march', 'april', 'may', 'june', 'all']
DAY_OF_WEEK = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'all']
def get_city(prompt):
"""
Asks user to specify a city to analyze data
Args:
(str) prompt - user input for the city to analyze
Returns:
(str) value - name of the city to analyze
"""
while True:
try:
value = input(prompt).lower()
except (ValueError, KeyboardInterrupt):
print("Sorry, I didn't understand that.")
continue
if value not in CITY_DATA:
print("Sorry, your response is invalid, try again...")
continue
else:
break
return value
def get_month(prompt):
"""
Asks user to specify month filter data.
get_month() method
Args:
(str) prompt - user input for the month to filter
Returns:
(str) value - name of the month to filter by, or "all" to apply no month filter
"""
while True:
try:
value = input(prompt).lower()
except (ValueError, KeyboardInterrupt):
print("Sorry, I didn't understand that.")
continue
if value not in MONTHS:
print("Sorry, your response is invalid, try again...")
continue
else:
break
return value
def get_day(prompt):
"""
Asks user to specify a day filter data.
Args:
(str) prompt - user input for day of week to filter
Returns:
(str) value - name of the day of week to filter by, or "all" to apply no day filter
"""
while True:
try:
value = input(prompt).lower()
except (ValueError, KeyboardInterrupt):
print("Sorry, I didn't understand that.")
continue
if value not in DAY_OF_WEEK:
print("Sorry, your response is invalid, try again...")
continue
else:
break
return value
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_DATA[city])
# converting 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) + 1
# filter by month to create the new dataframe
df = df[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[df['day_of_week'] == day.title()]
return df
def time_stats(df):
"""
Displays statistics on the most frequent times of travel.
using mode()[0] takes the first return mode value each time
"""
print('\nCalculating the most frequent times of travel...\n')
start_time = time.time()
# display the most common month
popular_month = df['month'].mode()[0]
print('Most popular month:', popular_month)
# display the most common day of week
popular_dow = df['day_of_week'].mode()[0]
print('Most popular day of week:', popular_dow)
# display the most common start hour
# extract hour from the Start Time column to create an hour column
df['hour'] = df['Start Time'].dt.hour
# find the most popular hour
popular_hour = df['hour'].mode()[0]
print('Most popular start hour:', popular_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."""
print('\nCalculating the most popular stations and trip...\n')
start_time = time.time()
# display most commonly used start station
popular_start = df['Start Station'].mode()[0]
print('Start station:', popular_start)
# display most commonly used end station
popular_end = df['End Station'].mode()[0]
print('End station:', popular_end)
# display most frequent combination of start station and end station trip
trip = (df['Start Station'] + ' - ' + df['End Station'])
popular_trip = trip.mode()[0]
print('Trip (Start - End):', popular_trip)
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."""
print('\nCalculating trip duration...\n')
start_time = time.time()
# display total travel time
total_travel_time = df['Trip Duration'].sum()
print('Total trip duration:', total_travel_time)
# display mean travel time
average_travel_time = df['Trip Duration'].mean()
print('Average trip duration:', average_travel_time)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-' * 40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating user statistics...\n')
start_time = time.time()
# Display counts of user types
user_types = df['User Type'].value_counts()
print('Breakdown of users\n')
print(user_types)
# Display counts of gender
try:
gender = df['Gender'].value_counts()
print('\nBreakdown of gender\n')
print(gender)
except KeyError:
print('Oops! Gender is not available in this city...\n')
# Display earliest, most recent, and most common year of birth
try:
earliest_dob = df['Birth Year'].min()
most_recent_dob = df['Birth Year'].max()
most_popular_dob = df['Birth Year'].mode()[0]
print('\nBreakdown of Year of Birth\n')
print('Most Popular year: {}'.format(most_popular_dob))
print('Oldest year: {}'.format(earliest_dob))
print('Youngest year: {}'.format(most_recent_dob))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-' * 40)
except KeyError:
print('Oops! Birth Year is not available in this city...\n')
print('-' * 40)
def user_individual_data(city):
"""Display 5 rows of individual trip"""
while True:
try:
df = pd.read_csv(CITY_DATA[city])
show_individual_data = input('\nWould you like to view 5 rows of individual trip?\nEnter yes or no.\n')
if show_individual_data.lower() == 'yes':
view_5_rows = df.head()
five_rows = view_5_rows.to_dict('records')
for row in five_rows:
print(row)
continue
elif show_individual_data.lower() == 'no':
break
except (ValueError, KeyboardInterrupt):
print("Sorry, your response is invalid, try again...")
def main():
while True:
# get user input for city (chicago, new york city, washington).
print('Would you like to analyze data for Chicago, New York City, or Washington?')
city = get_city("Please enter the city: ")
print('-' * 40)
# get user input for month (all, january, february, ... , june)
print('\nWhich month would like to filter data for?')
print('January, February, March, April, May, June or "all" to apply no month filter')
month = get_month("Please enter the month: ")
print('-' * 40)
# get user input for day of week (all, monday, tuesday, ... sunday)
print('\nWhich day would you like to filter data for?')
print('Monday, Tuesday, Wednesday, Thursday, Friday, Saturday Sunday or "all" to apply no day filter')
day = get_day("Please enter the day: ")
print('-' * 40)
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
user_individual_data(city)
try:
restart = input('\nWould you like to restart?\nEnter yes or no.\n')
if restart.lower() != 'yes':
break
except (ValueError, KeyboardInterrupt):
print("Sorry, your response is invalid, try again...")
if __name__ == "__main__":
main()