【问题标题】: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()
给出结果: