【问题标题】:How to plot a dictionary DataFrame looping through multiple keys?如何绘制通过多个键循环的字典DataFrame?
【发布时间】:2019-12-02 05:33:58
【问题描述】:

我有一个标记为 data 的数据框字典:which holds information about stocks and their pricing/volumes, etc...

我想遍历并绘制所有键和特定值。我正在升级我构建的原始程序,该程序仅适用于一种股票。我想通过给我的程序一个可以使用的股票列表来将它提升到一个新的水平,在这种情况下,股票列表称为tickers = ["LRCX", "FB", "COF"]

下面是我的原始程序如何仅绘制一只股票(又名一个数据框)。

 f, (ax1, ax2) = plt.subplots(1, 2, figsize=(14,5))
ax1.plot(dte_df["date"], dte_df["Close"])
ax1.set_xlabel("Date", fontsize=12)
ax1.set_ylabel("Stock Price")
ax1.set_title(f"{ticker} Close Price History")

# first Subplot (layer two)
ax1.plot(dte_df["date"], dte_df["High"], color="green")
ax1.set_xlabel("Date", fontsize=12)
ax1.set_ylabel("Stock Price")
ax1.set_title(f"{ticker} High Price History")

# first Subplot (layer three)
ax1.plot(dte_df["date"], dte_df["Low"], color="red")
ax1.set_xlabel("Date", fontsize=12)
ax1.set_ylabel("Stock Price")
ax1.set_title(f"{ticker} Low Price History")

# Second Subplot
ax2.plot(dte_df["date"], dte_df["Volume"], color="orange")
ax2.set_xlabel("Date", fontsize=12)
ax2.set_ylabel("Stock Price")
ax2.set_title(f"{ticker} Volume History")
plt.show()

上面的代码有两个子图。每日股价(最高价、最低价、收盘价)在一张图上,然后在另一张图上股票成交量。我正在尝试复制此代码,但要使用字典循环遍历键,而不是仅包含一只股票的数据框。我从来没有以这样的身份处理过字典,非常感谢您提前提供的任何帮助和指导,

干杯!

【问题讨论】:

    标签: python dictionary matplotlib plot


    【解决方案1】:

    这比 matplotlib 更像是一个熊猫问题,但无论如何。

    有几种方法可以遍历您的数据框。

    如果你有一个列名列表,那么你可以简单地使用 for 循环:

    l0 = ["L1",'L2']
    l1 = ["A1",'A2','A3']
    
    df = pd.DataFrame(np.random.random(size=(10,6)))
    df.columns = pd.MultiIndex.from_product([l0,l1])
    
    display(df)
    
    for l in l0:
        print('==== {:s} ====='.format(l))
        display(df.xs(l,axis=1))
    

    如果你想更通用,你可以使用 groupby 并迭代结果:

    for (l,temp_df) in df.groupby(level=0, axis=1):
        print('==== {:s} ===='.format(l))
        temp_df = temp_df.droplevel(level=0, axis=1)
        display(temp_df)
    

    【讨论】:

    • 我有点困惑,我已经建立了我的数据框字典,我可以不使用我的格式来绘制我上面提到的图表吗?还是我需要绕回并重新排列我的数据。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 2022-01-19
    • 2016-01-14
    • 2021-05-19
    • 2016-03-27
    • 2021-04-22
    • 1970-01-01
    相关资源
    最近更新 更多