【问题标题】:Iterate plot creation over columns of dataframe在数据框列上迭代绘图创建
【发布时间】:2021-11-21 10:44:18
【问题描述】:

我有一个数据框,其中包含来自道琼斯指数的 30 个时间序列的开盘价:

source=pd.read_html('https://en.wikipedia.org/wiki/Dow_Jones_Industrial_Average')
df = pd.DataFrame(source[1])
tickers_symbols=df['Symbol'].values.tolist()
dataset = pd.DataFrame()
for t in tickers_symbols:
    tmp = yf.download(t, period='5y', progress=False)
    tmp.reset_index(inplace=True)
    tmp['Ticker'] = t
    dataset = dataset.append(tmp, ignore_index=True)
dataset=dataset.drop(["Close", "High", "Low", "Adj Close", "Volume"], axis=1)
dataset = dataset.pivot_table(index="Date", columns="Ticker", values="Open")

我想做的是使用下面的函数为每只股票检索四个诊断图并将它们保存在特定文件夹中。

import statsmodels.tsa.api as smt
def tsplot2(y, title, lags=None, figsize=(12,8)):
        fig= plt.figure(figsize=figsize)
        layout=(2,2)
        ts_ax=plt.subplot2grid(layout, (0,0))
        hist_ax=plt.subplot2grid(layout, (0,1))
        acf_ax=plt.subplot2grid(layout, (1,0))
        pacf_ax=plt.subplot2grid(layout, (1,1))

        y.plot(ax=ts_ax)
        ts_ax.set_title(title, fontsize=14, fontweight='bold')
        y.plot(ax=hist_ax, kind='hist', bins=25)
        hist_ax.set_title('Histogram')
        smt.graphics.plot_acf(y, lags=lags, ax=acf_ax)
        smt.graphics.plot_pacf(y, lags=lags, ax=pacf_ax)
        sns.despine()
        plt.tight_layout()
        return ts_ax, acf_ax, pacf_ax

我尝试的方法如下:

for column in dataset:
    tsplot2(dataset[column], title=dataset[column], lags=50)
    plt.savefig(f"{figures}/"+column+"Plots.png", format="png")

但是,当我运行代码时,出现以下错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我不确定这在这种情况下意味着什么。有没有办法解决这个循环?

【问题讨论】:

  • 如前所述,title=column 而不是title=dataset[column],这是一个错字/不可重现。因此,出于这个原因,我投票结束答案。不要发布由错字类型问题引起的问题的答案,它们应该在 cmets 中被调用并标记,因为有一个特定的关闭标志 不可重现或由错字引起。这些问题通常被否决、关闭和删除,因为它们对社区没有好处。

标签: python dataframe matplotlib plot time-series


【解决方案1】:

你在函数调用中犯了一个错误:

tsplot2(dataset[column], title=dataset[column], lags=50)

应该是

tsplot2(dataset[column], title=column, lags=50)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多