绘制两个具有不同索引类型的熊猫数据框

时间:2019-11-29 00:17:22

标签: python pandas matplotlib

我有两个数据框...

具有整数索引的一个

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

我如何将它们相对绘制?

2 个答案:

答案 0 :(得分:1)

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

df2['Date']=df2.index

然后使用以下命令重置此DataFrame的索引:

df2=df2.reset_index()

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

答案 1 :(得分:1)

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()

给出结果:

enter image description here