Python 数据帧创建问题
以下函数用于加载数据。城市数据[城市] 映射到用户定义的城市对应的.csv文件 然而,当我“打印(df)”时,我在所有阶段都会得到一个空的数据帧。不知道这里发生了什么Python 数据帧创建问题,python,pandas,dataframe,Python,Pandas,Dataframe,以下函数用于加载数据。城市数据[城市] 映射到用户定义的城市对应的.csv文件 然而,当我“打印(df)”时,我在所有阶段都会得到一个空的数据帧。不知道这里发生了什么 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
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
"""
print (CITY_DATA[city])
df = pd.read_csv(CITY_DATA[city])
print (df)
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.weekday_name
if month != 'all':
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month) + 1
df = df[df['month'] == month]
if day != 'all':
df = df[df['day_of_week'] == day.title()]
print (df)
return df
任何帮助都将不胜感激 只是想澄清一下:什么时候你得到一个空的df,只是在返回语句之前,还是已经在开始的时候(在读取CSV文件之后)?在读取CSV文件之后,你确定文件存在并且有你想要的内容吗?您可以尝试
print(open(CITY_DATA[CITY]))
(或类似的方法),以查看Python是否能够正确地查找和读取该文件。