How to “smooth” a discrete/stepped signal in a vectorized way with numpy/scipy?

I have a signal like the orange one in the following plot that can only have integer values:

As you can see, the orange signal in a bit noisy and “waffles” between levels sometimes when its about to change to a new steady state. I’d like to “smooth” this effect and achieve the blue signal. The blue signal is the orange one filtered such that the transitions don’t occur until 3 samples in a row have made the jump to the next step. This is pretty easy if I loop through each sample manually and use a couple state variables to track how many times in a row I’ve jumped to a new step, but its also slow. I’d like to find a way to vectorize this in numpy. Any ideas?

Here’s an example of the non-vectorized way that seems to do what I want:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>up_count = 0
dn_count = 0
out = x.copy()
for i in range(len(out)-1):
if out[i+1] > out[i]:
up_count += 1
dn_count = 0
if up_count == 3:
up_count = 0
out[i+1] = out[i+1]
else:
out[i+1] = out[i]
elif out[i+1] < out[i]:
up_count = 0
dn_count += 1
if dn_count == 3:
dn_count = 0
out[i+1] = out[i+1]
else:
out[i+1] = out[i]
else:
dn_count = 0
up_count = 0
</code>
<code>up_count = 0 dn_count = 0 out = x.copy() for i in range(len(out)-1): if out[i+1] > out[i]: up_count += 1 dn_count = 0 if up_count == 3: up_count = 0 out[i+1] = out[i+1] else: out[i+1] = out[i] elif out[i+1] < out[i]: up_count = 0 dn_count += 1 if dn_count == 3: dn_count = 0 out[i+1] = out[i+1] else: out[i+1] = out[i] else: dn_count = 0 up_count = 0 </code>
up_count = 0
dn_count = 0
out = x.copy()
for i in range(len(out)-1):
    if out[i+1] > out[i]:
        up_count += 1
        dn_count = 0

        if up_count == 3:
            up_count = 0
            out[i+1] = out[i+1]
        else:
            out[i+1] = out[i]
    elif out[i+1] < out[i]:
        up_count = 0
        dn_count += 1

        if dn_count == 3:
            dn_count = 0
            out[i+1] = out[i+1]
        else:
            out[i+1] = out[i]
    else:
        dn_count = 0
        up_count = 0

EDIT:
Thanks to @Bogdan Shevchenko for this solution. I already have numpy and scipy available, so rather than get pandas involved here’s my numpy/scipy version of his answer:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def ffill(arr, mask):
idx = np.where(~mask, np.arange(mask.shape[0])[:, None], 0)
np.maximum.accumulate(idx, axis=0, out=idx)
return arr[idx, np.arange(idx.shape[1])]
x_max = scipy.ndimage.maximum_filter1d(x, 3, axis=0, origin=1, mode="nearest")
x_min = scipy.ndimage.minimum_filter1d(x, 3, axis=0, origin=1, mode="nearest")
x_smooth = ffill(x, x_max!=x_min)
</code>
<code>def ffill(arr, mask): idx = np.where(~mask, np.arange(mask.shape[0])[:, None], 0) np.maximum.accumulate(idx, axis=0, out=idx) return arr[idx, np.arange(idx.shape[1])] x_max = scipy.ndimage.maximum_filter1d(x, 3, axis=0, origin=1, mode="nearest") x_min = scipy.ndimage.minimum_filter1d(x, 3, axis=0, origin=1, mode="nearest") x_smooth = ffill(x, x_max!=x_min) </code>
def ffill(arr, mask):
    idx = np.where(~mask, np.arange(mask.shape[0])[:, None], 0)
    np.maximum.accumulate(idx, axis=0, out=idx)
    return arr[idx, np.arange(idx.shape[1])]

x_max = scipy.ndimage.maximum_filter1d(x, 3, axis=0, origin=1, mode="nearest")
x_min = scipy.ndimage.minimum_filter1d(x, 3, axis=0, origin=1, mode="nearest")
x_smooth = ffill(x, x_max!=x_min)

0

There could be a lot of different strategies, based on DataFrame.rolling processing. In example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>t = pd.Series([
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
1, 2, 1, 2, 1, 1, 2, 2, 3, 1, 2,
2, 1, 1, 2, 1, 1, 1, 1, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
min_at_row = 3
t_smoothed = t.copy()
t_smoothed[
t.rolling(min_at_row, min_periods=1).max() !=
t.rolling(min_at_row, min_periods=1).min()
] = None
t_smoothed = t_smoothed.ffill()
</code>
<code>t = pd.Series([ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 1, 1, 2, 2, 3, 1, 2, 2, 1, 1, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]) min_at_row = 3 t_smoothed = t.copy() t_smoothed[ t.rolling(min_at_row, min_periods=1).max() != t.rolling(min_at_row, min_periods=1).min() ] = None t_smoothed = t_smoothed.ffill() </code>
t = pd.Series([
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 
    1, 2, 1, 2, 1, 1, 2, 2, 3, 1, 2, 
    2, 1, 1, 2, 1, 1, 1, 1, 2, 2, 2, 
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
min_at_row = 3

t_smoothed = t.copy()
t_smoothed[
    t.rolling(min_at_row, min_periods=1).max() != 
    t.rolling(min_at_row, min_periods=1).min()
] = None
t_smoothed = t_smoothed.ffill()

Result looks like what you want to obtain:

If you want to stay with numpy only, without pandas, use np.lib.stride_tricks.sliding_window_view(t, min_at_row).max(axis=1) instead of t.rolling(min_at_row).max() (and analogously with min), but be aware that it will return array without first (min_at_row - 1) values

You can also use t_smoothed.shift(-min_at_row + 1) to remove delay of smoothened signal.

0

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật