【问题标题】:Plot Two Panda Dataframes That Have Different Index Types绘制两个具有不同索引类型的 Panda 数据框
【发布时间】:2019-11-29 00:17:22
【问题描述】:

我有两个数据框...

具有整数索引的:

Date     Close
1  1998-01-02  1.000000
2  1998-01-05  1.002082
...          ...       ...
5511  2019-11-26  3.220914
5512  2019-11-27  3.234360

[5513 rows x 2 columns]

另一个看起来像使用日期值作为索引的:

Close
1998-01-02  1.000000
1998-01-05  1.002082
...          ...
2019-11-26  3.220914
2019-11-27  3.234360

[5513 rows x 1 columns

我如何让它们相互对抗?

【问题讨论】:

  • 为了澄清,您想在日期上绘制关闭值?
  • 没错
  • 对于两组数据,在一个图表上。这可能吗?

标签: python pandas matplotlib


【解决方案1】:

使用以下方法为第二个 DataFrame 创建一个“日期”列:

df2['Date']=df2.index

然后使用以下方法重置此 DataFrame 的索引:

df2=df2.reset_index()

现在,两个数据帧具有相同的索引,并且具有 “日期”和“关闭”列,以便您可以以类似的方式绘制它们。

【讨论】:

    【解决方案2】:
    import pandas as pd
    import matplotlib.pyplot as plt
    
    # Initialize exampe dataframes
    df1 = pd.DataFrame({
        "Date": ["1998-01-02", "1998-01-05", "2019-11-26", "2019-11-27"],
        "Close": [1.000000, 1.002082, 3.220914, 3.234360],
    })
    df2 = pd.DataFrame(
        index=["2000-01-02", "2002-01-05", "2015-11-26", "2017-11-27"],
        data={"Close": [1.000000, 1.502082, 2.220914, 3.034360]},
    )
    
    # Convert date strings to `datetime` objects
    df1["Date"] = pd.to_datetime(df1["Date"])
    df2.index = pd.to_datetime(df2.index)
    
    # Create plot
    plt.plot(df1["Date"], df1["Close"], df2.index, df2["Close"])
    plt.show()
    

    给出结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-07
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 2019-01-31
      • 2012-05-08
      相关资源
      最近更新 更多