Python - ejercicio_udacity - hacer un filtrado sobre un documento .cvs

 
Vista:
sin imagen de perfil
Val: 2
Ha disminuido su posición en 7 puestos en Python (en relación al último mes)
Gráfica de Python

ejercicio_udacity - hacer un filtrado sobre un documento .cvs

Publicado por Xabier (1 intervención) el 09/10/2020 12:42:27
# Hola!! Estoy teniendo problemas para arrancar el programa. La idea es hacer un filtrado inicial sobre un documento .cvs.
1. Elegir una ciudad: Chicago, Washington o New York City.
2. Elegir si deseamos filtrar por mes, dia de la semana o no filtrar (no sé como programar este último). También tengo problemas a la hora de filtrar por día de la semana y mes, ya que se me realiza la pregunta para filtrar por ambos siempre, elija lo que elija.
3. No me funciona cuando el convertir las fechas (que son un string) a fecha ( a través de "datetime").

Muchísimas gracias por vuestra ayuda!!


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
from datetime import datetime
import pandas as pd
import numpy as np
 
CITY_DATA = { 'chicago': 'chicago.csv',
              'new york city': 'new_york_city.csv',
              'washington': 'washington.csv' }
 
def get_city():
    """
    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
    """
     # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
    city_csv=''
    select_city=''
 
    while select_city not in ['Chicago','New York City', 'Washington']:
 
        select_city = input('Hello! Let\'s explore some US bikeshare data! Choose a city between Chicago, New York City and Washington')
        if select_city.title()=='Chicago':
            city_csv='chicago.csv'
            return city_csv
        elif select_city.title()=='New York City':
            city_csv='new_york_city.csv'
            return city_csv
        elif select_city.title()=='Washington':
            city_csv='washington.csv'
            return city_csv
        else:
            print("You did not enter any suggested city. Please, enter Chicago, New York City or Washington"
                  "\n")
def time_filter():
    time_filt=''
    while time_filt not in ['month', 'wday', 'none']:
        time_filt=input("Would you like to filter by month, day of the week or no filtering at all? Please,type 'month', 'wday' or 'none'")
        if time_filt.lower()=='month':
            return time_filt
        if time_filt.lower()=='wday':
            time_filt
            return time_filt
        if time_filt.lower()=='none':
            return time_filt
        else:
            print("The parameter you entered is not correct. Please, type 'month', 'wday' or 'none'")
# TO DO: get user input for month (all, january, february, ... , june)
def get_month():
    MONTHS_DATA={'January':1,'February':2,'March':3,'April':4,'May':5,'June':6}
    select_month=''
    while select_month not in MONTHS_DATA:
        select_month=input("Please, enter a month from the following: January, February, March, April, May and June")
        if select_month.title() not in MONTHS_DATA:
            print("The month selected is not between the mentioned selection. Please, type January, February, March, April, May or June")
        select_month=MONTHS_DATA[(select_month.title())]#--------->>Do return the index(number of the month) with this?
        return select_month
    # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
def get_wday():
    WDAY_DATA=['Monday', 'Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday','All']
    select_wday=''
    while select_wday.title() not in WDAY_DATA:
         select_wday=input("Please, select a weekday ('Monday', 'Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday') or type 'All' to choose all of"     "them")
    if select_wday.title() not in WDAY_DATA:
        print ("The selected day of the week is not correct. Please tpye 'Monday', 'Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday' or type 'All' to choose all of them")
    elif select_wday.title()=="Monday" or select_wday.title()=="Tuesday" or select_wday.title()=="Wednesday" or select_wday.title()=="Thursday" or           select_wday.title()=="Friday" or select_wday.title()=="Saturday" or select_wday.title()=="Sunday":
        return select_wday
    else:
        select_wday.title=WDAY_DATA[0:] #for "All" input
        return select_wday.title()
def load_data(city_csv,time_filt,select_month, select_wday):
    """
    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
    """
    df=pd.read_csv(city_csv)
    return df
def most_common_month(df):
    """Displays statistics on the most frequent times of travel."""
    print('\nCalculating The Most Frequent Times of Travel...\n')
    df['Start Time']=pd.datetime['Start Time'] #-------->>> Is it correct inside this function??
    df['End Time']=pd.datetime['End Time']#---->>>>Is it correct inside this function??
 
    # TO DO: display the most common month
    months=['January','February','March','April','May','June']
    index_month=int(df['Start Time'].months.dt.mode())
    most_common_month=months[index_month-1]
    print("The most common month is {}".format(most_common_month))
 
 
def most_common_wday(df):
 
    df['Start Time'] = pd.datetime(df['Start Time'])# I guess it is not required anymore, as it was defined in the function  "most_common_month(df)"
 
    # TO DO: display the most common day of week
    days=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
    index_wday=int(df['Start Time'].dayofweek.dt.mode())
    most_common_wday=days[index_day]
 
    print("The most common day of the week is {}".format(most_common_wday))
 
def most_common_start_hour(df):
 
    df['Start Time'] = pd.datetime(df['Start Time'])# # I guess it is not required anymore, as it was defined in the function  "most_common_month(df)"
 
    # TO DO: display the most common start hour
    most_common_starth=int(df['Start Time'].hour.dt.mode())
 
    if most_common_starth==0:
        apm='am'
 
    elif most_common_starth>0 and most_common_starth<13:
        apm='am'
 
    elif most_common_starth>=13 and most_common_starth<=24:
        apm='pm'
 
    print("The most common start hour is {}{}".format(most_commont_starth,apm))
 
def station_stats(df):
    """Displays statistics on the most popular stations and trip."""
 
    print('\nCalculating The Most Popular Stations and Trip...\n')
 
 
    # TO DO: display most commonly used start station
    most_commonly_start_st=df['Start Station'].mode()
    print("The most commonly used start station is {}".format(most_commonly_start_st))
 
    # TO DO: display most commonly used end station
    most_commonly_end_st=df['End Station'].mode()
    print("The most commonly used end station is {}".format(most_commonly_end_st))
 
    # TO DO: display most frequent combination of start station and end station trip
    df['Trip']=df['Start Station'].str.cat(df['End Station'],sep='to')
    most_common_trip=df['Trip'].mode()
    print("The most common trip is {}".format(most_common_trip))
 
def trip_duration_stats(df):
    """Displays statistics on the total and average trip duration."""
 
    print('\nCalculating Trip Duration...\n')
 
    # TO DO: display total travel time
    trip_duration=df['Trip Duration'].sum()
    print("The total trip duration is {}s".format(trip_duration))
 
    # TO DO: display mean travel time
 
    trip_mean_dur=df['Trip Duration'].mean()
 
    print("The total trip duration is {}s".format(trip_mean_dur))
 
 
def user_stats(df,city_csv):
    """Displays statistics on bikeshare users."""
 
    print('\nCalculating User Stats...\n')
 
    # TO DO: Display counts of user types
    cust=0
    suscr=0
    while df['User Type']=='Suscriber' or df['User Type']=='Customer':
 
      if df['User Type']=='Suscriber':
          suscr+=1
 
      else:
          cust+=1
 
    print("The amount of suscribers is {}".format(suscr))
    print("The amount of suscribers is {}".format(cust))
 
 
    # TO DO: Display counts of gender
 
    if city_csv=='chicago.csv' or city_csv=='new_york_city.csv':
 
      female=0
      male=0
 
      while df['Gender']=='Female' or df['Gender']=='Male' or df['Gender']=='':
              if df['Gender']=='Female':
                  female+=1
              elif df['Gender']=='Male':
                  male+=1
              else:
                  female=female
                  male=male
 
      print("The amount of males is {}".format(male))
      print("The amount of females is {}".format(female))
 
    # TO DO: Display earliest, most recent, and most common year of birth
    earliest_birthy=str(int(df['Birth Year']).min())
    most_recent_birthy=str(int(df['Birth Year']).max())
    most_common_birthy=str(int(df['Birth Year']).mode())
 
    print("The earliest year of birth is {}".format(earliest_birthy))
    print("The most recent year of birth is {}".format(most_recent_birthy))
    print("The most common year of birth is {}".format(most_common_birthy))
 
 
def main():# XL- Mirar que es exactamente lo que se hace de aqui hacia abajo
 
    while True:
        city_csv=get_city()
        time_filt=time_filter()
        select_month=get_month()
        select_wday=get_wday()
        df = load_data(city_csv,time_filt, select_month, select_wday)#XL-Las variables son estas???????
 
        most_common_month(df)
        most_common_wday(df)
        most_common_start_hour(df)
        station_stats(df)
        trip_duration_stats(df)
        user_stats(df, city_csv)
 
        restart = input('\nWould you like to restart? Enter yes or no.\n')
        if restart.lower() != 'yes':
            break
 
 
if __name__ == "__main__":
	main()
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder