如何正确绘制具有零值和 DateTimeIndex 的 Pandas Series?

问题描述 投票:0回答:1

我有一个 Pandas 系列,有许多零值和 DateTimeIndex。我只想用一些零值来绘制它们并正确处理日期时间间距。

例如,该系列如下。简单的图显示了太多的零。我只想在非零值之前和之后显示一些零。同时,正确隐藏之间的日期。

ser_tmp = pd.Series(0, index=pd.date_range('2020-01-01', '2020-01-30'))
ser_tmp.loc[[pd.Timestamp('2020-01-03'), pd.Timestamp('2020-01-04'), pd.Timestamp('2020-01-23'), pd.Timestamp('2020-01-24')]] = 1

ser_tmp.plot()

enter image description here

替换全零后的绘图不是我想要的。

ser_tmp.replace(0, np.nan).plot()

enter image description here

我想要的是

ser_tmp2
之类的东西。但绘制
ser_tmp2
并没有隐藏
2020-01-06
2020-01-21
之间的日期差距。此外,我想自动检测日期,而不是像
ser_tmp2
那样手动设置零。

ser_tmp2 = ser_tmp.replace(0, np.nan).copy()
ser_tmp2.loc[[pd.Timestamp('2020-01-01'), pd.Timestamp('2020-01-02'), pd.Timestamp('2020-01-05'), pd.Timestamp('2020-01-06'), pd.Timestamp('2020-01-21'), pd.Timestamp('2020-01-22'), pd.Timestamp('2020-01-25'), pd.Timestamp('2020-01-26')]] = 0

ser_tmp2 = ser_tmp2.dropna()

ser_tmp2
ser_tmp2.plot()

enter image description here

enter image description here

python pandas plot
1个回答
0
投票

如果我没听错,你想删除多个连续的零。

我的解决方案:

ser_tmp = pd.Series(0, index=pd.date_range('2020-01-01', '2020-01-30'))
ser_tmp.loc[[pd.Timestamp('2020-01-03'), pd.Timestamp('2020-01-04'), pd.Timestamp('2020-01-23'), pd.Timestamp('2020-01-24')]] = 1
ser_tmp.index = ser_tmp.index.strftime('%Y-%m-%d')  # Set the index to string so it will not automatically add missing dates
ser_tmp.drop(ser_tmp[(ser_tmp == 0) & (ser_tmp.shift(1) == 0) & (ser_tmp.shift(-1) == 0)].index, inplace=True)  # Drop all zeros values that have zero before and zero after as values

ser_tmp.plot(rot=45)

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.