【问题标题】:Plotting two timeseries DataFrames with matplotlib and some missing dates in one DataFrame使用 matplotlib 绘制两个时间序列数据帧和一个数据帧中的一些缺失日期
【发布时间】:2020-06-11 21:26:07
【问题描述】:

我有两个 X 轴上有日期的 DataFrame。我想用两个比例将它们绘制在一个图中。

数据帧 #1

print(df_daily.head())
        date  senti-pol  senti-vader
0 2019-10-01  -0.060639    -0.174223
1 2019-10-02  -0.080265     0.090761
2 2019-10-03  -0.186335    -0.645464
3 2019-10-04   0.014124    -0.043164
4 2019-10-05  -0.035157     0.275379

数据帧 #2

print(df_dbk.head())
             Open   High    Low  Close  Adj Close    Volume
Date                                                       
2019-10-02  6.650  6.720  6.560  6.566      6.566  15527318
2019-10-04  6.520  6.531  6.369  6.480      6.480  16042648
2019-10-07  6.489  6.489  6.348  6.481      6.481  11130966
2019-10-08  6.515  6.529  6.205  6.304      6.304  13736758
2019-10-09  6.300  6.375  6.256  6.294      6.294   8625379

第二个数据框缺少一些日期。我想这是我尝试绘制它时的问题(数据示例):

from io import StringIO
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df_senti = '        date  senti-pol  senti-vader\n0 2019-10-01  -0.060639    -0.174223\n1 2019-10-02  -0.080265     0.090761\n2 2019-10-03  -0.186335    -0.645464\n3 2019-10-04   0.014124    -0.043164\n4 2019-10-05  -0.035157     0.275379'
df_daily = pd.read_csv(StringIO(df_senti),sep='\s+')
print(df_daily)

import yfinance as yf
df_dbk = yf.download("DBK.DE", start="2019-10-02", end="2019-10-10", interval="1d") # day+1 otherwise wrong data
print(df_dbk)

fig, ax1 = plt.subplots()

color = 'tab:red'
ax1.set_xlabel('date')
ax1.set_ylabel('sentiment', color=color)
ax1.plot(df_daily['date'], df_daily['senti-vader'], color=color)
ax1.tick_params(axis='y', labelcolor=color)

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

color = 'tab:blue'
ax2.set_ylabel('share price', color=color)  # we already handled the x-label with ax1
ax2.plot(df_dbk['Date'], df_dbk['Adj Close'], color=color)
ax2.tick_params(axis='y', labelcolor=color)

fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.show()

我收到的错误是

KeyError: 'Date'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-11-e4156bac397f> in <module>
     24 color = 'tab:blue'
     25 ax2.set_ylabel('share price', color=color)  # we already handled the x-label with ax1
---> 26 ax2.plot(df_dbk['Date'], df_dbk['Adj Close'], color=color)
     27 ax2.tick_params(axis='y', labelcolor=color)

有没有一种很好的方法可以忽略第二个 DataFrame 中缺失的日期?

【问题讨论】:

    标签: python python-3.x pandas matplotlib


    【解决方案1】:

    'Date' 不是数据框 dbk_df_csv 中的列。它似乎是您的索引的名称。这就是你KeyError 告诉你的。

    试试这个

    ax2.plot(dbk_df_csv.index, dbk_df_csv['Adj Close'], color=color)
    

    事实上,你可以省略 x 值,它会从数据中推断出来:

    ax2.plot(dbk_df_csv['Adj Close'], color=color)
    

    【讨论】:

    • 这没有帮助。我用实际数据的摘录编辑了我的代码示例。
    【解决方案2】:

    我找到了解决问题的方法。问题在于不同类型的 x 值。

    print(type(df_daily.index))
    <class 'pandas.core.indexes.numeric.Int64Index'>
    
    print(type(df_daily['date']))
    <class 'pandas.core.series.Series'>
    
    print(type(df_dbk.index))
    <class 'pandas.core.indexes.datetimes.DatetimeIndex'>
    

    根据@busybear 的回答,我想将索引从df_daily 转换。

    df_daily['Date'] = pd.to_datetime(df_daily['date'])
    df_daily = df_daily.set_index('Date')
    
    print(df_daily)
                     date  senti-pol  senti-vader
    Date                                         
    2019-10-01 2019-10-01  -0.060639    -0.174223
    2019-10-02 2019-10-02  -0.080265     0.090761
    2019-10-03 2019-10-03  -0.186335    -0.645464
    2019-10-04 2019-10-04   0.014124    -0.043164
    2019-10-05 2019-10-05  -0.035157     0.275379
    
    print(type(df_daily.index))
    <class 'pandas.core.indexes.datetimes.DatetimeIndex'>
    

    通过更改索引,我能够生成绘图。

    fig, ax1 = plt.subplots(figsize=(20, 10))
    
    color = 'tab:red'
    ax1.set_xlabel('date')
    ax1.set_ylabel('sentiment', color=color)
    ax1.plot(df_daily.index, df_daily['senti-vader'], color=color, marker='.')
    ax1.tick_params(axis='y', labelcolor=color)
    ax1.tick_params(axis='x', rotation=45)
    
    ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
    
    color = 'tab:blue'
    ax2.set_ylabel('share price', color=color)  # we already handled the x-label with ax1
    ax2.plot(df_dbk.index, df_dbk['Adj Close'], color=color, marker='.')
    ax2.tick_params(axis='y', labelcolor=color)
    ax2.tick_params(axis='x', rotation=45)
    
    fig.tight_layout()  # otherwise the right y-label is slightly clipped
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2016-02-22
      • 2019-07-02
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 2022-09-24
      • 1970-01-01
      • 2022-01-06
      • 2020-10-09
      相关资源
      最近更新 更多