首页 > 解决方案 > 有没有办法使用 Matplotlib 中的时间序列数据生成类方波?

问题描述

我对 Python 和 Matplotlib 比较陌生。有没有办法使用熊猫系列(即时间序列)生成“方形”波?

例如,以下值在系列中:

12、34、97、-4、-100、-9、31、87、-5、-2、33、13、1

显然,如果我绘制这个系列,它不会显示为方波。

有没有办法告诉 Python 如果值大于零,则在零上方绘制一致的水平线(例如,假设将线绘制在 1 处),如果值低于零,则在零下方绘制一条水平线(例如,在-1)?

由于这是一个时间序列,我不希望它是一个完美的正方形。

标签: pythonpandasmatplotlib

解决方案


用作np.clip

x=[12, 34, 97, -4, -100, -9, 31, 87, -5, -2, 33, 13, 1]
np.clip(x, a_min=-1, a_max=1)

array([ 1,  1,  1, -1, -1, -1,  1,  1, -1, -1,  1,  1,  1])

或者Series.clip

s = pd.Series(x)
s = s.clip(lower=-1, upper=1)

如果它的值介于 >=-1 到 <=1 之间,则使用np.where

x = np.where(np.array(x)>0, 1, -1) # for series s = np.where(s>0, 1, -1)

print(s) 
0     1
1     1
2     1
3    -1
4    -1
5    -1
6     1
7     1
8    -1
9    -1
10    1
11    1
12    1
dtype: int64

推荐阅读