1

这可能是重复的,但我找不到解决方案,所以在这里:

我正在尝试将以下数据框组合到一个图中。DF1:

quarter   count
2017-1    1
2017-2    1
2017-3    1
2017-4    2
2018-2    5
2018-3    2

使用 Df2:

quarter   count
2017-1    9
2017-2    16
2017-3    6
2017-4    15
2018-1    14
2018-2    17
2018-3    20
2018-4    16

但是,如果我运行以下命令:

ax = plt.gca()
Df1.plot(x = 'quarter', y = 'count', ax = ax)
Df2.plot(x = 'quarter', y = 'count', ax = ax)
plt.xticks(Df2.index, Df2['quarter'].values)

事情出错了,因为它只是在“2018-1”和“2018-2”点绘制了 Df1 的“2018-2”和“2018-3”值。我猜这是因为 Df1 没有“2018-1”值。知道如何解决这个问题吗?(让 Df1 的情节在 2018-1 年为零?)

4

1 回答 1

2

使用reindex_likefillna

df1 = df1.set_index('quarter').reindex_like(df2.set_index('quarter')).reset_index().fillna(0)

ax = plt.gca()
df1.plot(x = 'quarter', y = 'count', ax = ax)
df2.plot(x = 'quarter', y = 'count', ax = ax)
plt.xticks(df2.index, df2['quarter'].values)
plt.show()

输出图如下所示:

在此处输入图像描述

于 2018-12-27T12:32:08.963 回答