pythonperformancerolling-computation

Change adjacent elements of a python series


I have a python series which has boolean values. Wherever there is a True in the series, I want the previous 5 values and the next 6 values to be true.

I could achieve it using a for loop but I want to know if I can achieve it using a built in function.


Solution

  • Here's another possible solution which consists of:

    1. Identifying which indices have a True
    2. Iterating over each of these and adjusting neighboring values
    x = np.array([
        0, 1, 0, 0, 0,
        0, 0, 0, 0, 0,
        0, 0, 0, 0, 0,
        1, 1, 1, 1, 1,
        0, 0, 0, 0, 0,
        0, 0, 0, 0, 0,
        0, 0, 0, 1, 1]).astype(bool)
    
    # step 1: find indices where entries are True
    true_indices = [i for i, value in enumerate(s) if value]
    
    # step 2: adjust neighboring values
    for idx in true_indices:
        s[max(0, idx-5):min(len(s), idx+7)] = True
    

    Thanks to @dankal444 for the little example :)