【发布时间】:2022-10-08 05:00:40
【问题描述】:
我想在我的 Udacity 项目中获得一些帮助。这就是美国著名的共享单车项目! 您应该创建一个交互式程序,要求用户输入三个城市之一:芝加哥、华盛顿或纽约市。前 6 个月和工作日之一。 一个函数应该获取三个过滤器,城市,月份和日期。然后另一个函数应该加载过滤器并创建一个过滤的 DataFrame。然后进行一些统计。
每当我尝试通过选择特定月份而不是全部和特定日期而不是全部来过滤数据时,我的问题就会发生......似乎由于某种原因它返回一个空的DataFrame! 我已经查看了几个代码,我的加载功能很简单!
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
"""
#let's first load the data from the csv file!
df = pd.read_csv(CITY_DATA[city])
#now, we convert the start time column to datatime as in practice problem
df['Start Time'] = pd.to_datetime(df['Start Time'])
#now we get the month and day from Start Time like in the practice problem
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.day_name
df['hour'] = df['Start Time'].dt.hour
#now let's get the filters for month and day if the user didn't choose all
if month != 'all':
#first we get the index of the month then we create a new filtered df
month = MONTH_DATA.index(month)
df = df[df['month']==month]
if day != 'all':
df= df[df['day_of_week'] == day.title()]
return df
例如,当我过滤 jan 和 sun 时,它给了我这个:
Empty DataFrame
Columns: [Unnamed: 0, Start Time, End Time, Trip Duration, Start Station, End Station, User
Type, Gender, Birth Year, month, day_of_week, hour]
Index: []
有什么帮助吗? :)
【问题讨论】:
-
欢迎来到堆栈溢出。请阅读How to Ask 和formatting help 并确保代码与您实际拥有的完全相同。您显示的内容会导致语法错误。另外,阅读stackoverflow.com/help/minimal-reproducible-example 并解释:为什么应该结果不一样?您对这些过滤器的期望结果究竟是什么?您能否向我们展示导致问题的准确输入,以及准确对应的所需输出?
-
最后,先自己尝试debug代码。例如,
df['month']列是什么样的?列的数据类型是什么?当df = df[df['month']==month]发生时,month的值是多少?它的类型是什么?这一切有意义吗?对于日列也是如此。还要确保首先正确读取df。当您在文本编辑器或电子表格程序中检查相应文件时,它是否看起来像它应该的样子?