Python 绘制具有不同索引类型的两个Panda数据帧

Python 绘制具有不同索引类型的两个Panda数据帧,python,pandas,matplotlib,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.00

我有两个数据帧

一个具有整数索引:

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

如何将它们相互绘制?

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

df2['Date']=df2.index
df2=df2.reset_index()
然后使用以下命令重置此数据帧的索引:

df2['Date']=df2.index
df2=df2.reset_index()
现在,这两个数据帧具有相同的索引,并且
“日期”和“关闭”列,以便您可以以类似的方式绘制它们。

使用以下命令为第二个数据帧创建“日期”列:

df2['Date']=df2.index
df2=df2.reset_index()
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()
然后使用以下命令重置此数据帧的索引:

df2['Date']=df2.index
df2=df2.reset_index()
现在,这两个数据帧具有相同的索引,并且 “日期”和“关闭”列,以便您可以以类似的方式绘制它们

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()
结果如下:

结果如下:


为了澄清,您想在一个图表上绘制该日期的收盘价?这对两组数据都是正确的。这可能吗?为了澄清,您希望在一个图表上绘制该日期的收盘价?这对两组数据都是正确的。可能吗?