【发布时间】:2017-07-10 10:42:54
【问题描述】:
我在 udacity 学习(我是新手),我坚持这一点。我复制代码并运行但没有输出
这是 udacity 链接https://www.youtube.com/watch?v=vmF6iEQzC2A
*我的csv文件和视频不一样
这是我的代码
"""Slice and plot"""
import os
import pandas as pd
import matplotlib.pyplot as plt
def plot_selected(df, columns, start_index, end_index):
plot_data(df.ix[start_index:end_index,columns],title="Selected Data")
def symbol_to_path(symbol, base_dir="data"):
"""Return CSV file path given ticker symbol."""
return os.path.join(base_dir, "{}.csv".format(str(symbol)))
def get_data(symbols, dates):
"""Read stock data (adjusted close) for given symbols from CSV files."""
df = pd.DataFrame(index=dates)
if 'EURUSDCSV' not in symbols: # add EUR for reference, if absent
symbols.insert(0, 'EURUSDCSV')
for symbol in symbols:
df_temp = pd.read_csv(symbol_to_path(symbol), index_col='DateTime',
parse_dates=True, usecols=['DateTime', 'Close'], na_values=['nan'])
df_temp = df_temp.rename(columns={'Close': symbol})
df = df.join(df_temp)
if symbol == 'EURUSDCSV': # drop dates SPY did not trade
df = df.dropna(subset=["EURUSDCSV"])
return df
def plot_data(df, title="Stock prices"):
"""Plot stock prices with a custom title and meaningful axis labels."""
ax = df.plot(title=title, fontsize=12)
ax.set_xlabel("Date")
ax.set_ylabel("Price")
plt.show()
def test_run():
# Define a date range
dates = pd.date_range('2015-01-01', '2015-12-31')
# Choose stock symbols to read
symbols = ['EURUSDCSV', 'USDJPYcsv'] # SPY will be added in get_data()
# Get stock data
df = get_data(symbols, dates)
# Slice and plot
plot_selected(df, ['EURUSDCSV', 'USDJPYcsv'], '2015-01-01', '2015-12-31')
if __name__ == "__main__":
test_run()
【问题讨论】:
-
def语句之前的行中有错字:plot_data(df.ix[start_index:end_index,columns],title="Selected Data)"应该是plot_data(df.ix[start_index:end_index,columns],title="Selected Data")。 -
谢谢托马斯。但它仍然不起作用。没有错误和输出。应该出现图表。
-
可能有多种原因——很难说,因为我们没有您的意见。如果我是你,我会首先检查
plot_data中的df是否确实包含一些数据(试试print(df)或print(len(df)))。如果为空,则从那里开始搜索。 -
我在“return df”下方的相同位置键入“print(df)”。无输出
-
在
return df之前输入,否则print命令将不会被执行。