我有两个数据帧。
具有整数索引的一个:
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我如何将它们相互对比?
发布于 2019-11-29 08:41:57
使用以下命令为第二个DataFrame创建一个'Date‘列:
df2['Date']=df2.index然后使用以下命令重置此DataFrame的索引:
df2=df2.reset_index()现在,这两个数据帧具有相同的索引,并且具有"Date“和"Close”列,因此您可以用类似的方式绘制它们。
发布于 2019-11-29 08:58:01
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()作为结果给予:

https://stackoverflow.com/questions/59097418
复制相似问题