Home > OS >  How to eliminate outstanding values in python?
How to eliminate outstanding values in python?

Time:01-14

I have an array of zeros and ones which are intended to be of some defined width. It's a processed signal and some spikes suddenly appear during processing. I want to get rid of this spikes just to set them to the same values as surrending elements are set to.

The plot of my array

I did what I wanted in a simple way like this:

for ind, x in enumerate(signal_bool):
    if ind == 0 or ind == len(signal_bool) - 1:
        continue

    if signal_bool[ind-1] == signal_bool[ind 1]:
        signal_bool[ind] = signal_bool[ind-1]

But I'm curious if there is any eloquent way to obtain the same result.

CodePudding user response:

You can simplify the code a bit:

for ind in range(1, len(signal_bool) - 1):
    if signal_bool[ind - 1] == signal_bool[ind   1]:
        signal_bool[ind] = signal_bool[ind - 1]

This approach removes the enumerate and first if/continue statement, since range will only operate on the middle indexes.

CodePudding user response:

Maybe it helps.

if signal_bool is pd.Series:

ind = signal_bool.shift(-1) == signal_bool.shift(1)
signal_bool[ind] = signal_bool.shift(-1)[ind]

if signal_bool is numpy:

ind = np.roll(signal_bool, -1) == np.roll(signal_bool, 1)
signal_bool[ind] = np.roll(signal_bool, -1)[ind]
  • Related