I have a vector with signals with values of 1 or -1. I want to have a second vector that computes the cumulative sum of consecutive signals with the same value and restarts the cumulative sum every time the signal change. Here is an example:
signal = [1 1 1 -1 -1 -1 -1]
cum_sum = [1 2 3 -1 -2 -3 -4]
I have large data to be computed and want to do it as efficiently as possible. My code right now does the job but it takes time and is not taking advantage of numpy efficiency:
import numpy as np
# Signal values to be analyzed
signal = np.array([1,1,1,-1,-1,-1,-1], dtype=int)
# Vector with previous value of signal
signal_prev = signal[:-1]
signal_prev = np.pad(signal_prev,(1,0), mode='constant', constant_values=(0))
#Array with signal values in first column and previous values in second column
arr = np.array([signal,signal_prev], dtype=int)
arr = np.transpose(arr)
print(arr)
""" Array with signal values and previous values
[[ 1 0]
[ 1 1]
[ 1 1]
[-1 1]
[-1 -1]
[-1 -1]
[-1 -1]]
"""
#create an empty array to append cumulative sum
signal_sum = np.array([], dtype=int)
# compute the cumulative sum iterating row by row
for x in arr:
if np.sign(x[0]*x[1]) > 0:
signal_sum = np.append(signal_sum, signal_sum[-1] + x[1])
else:
signal_sum= np.append(signal_sum, x[0])
arr_sum = np.array([signal, signal_sum])
arr_sum = np.transpose(arr_sum)
print(arr_sum)
""" Array with signal values and cumulative sum restarted with signal change
[[ 1 1]
[ 1 2]
[ 1 3]
[-1 -1]
[-1 -2]
[-1 -3]
[-1 -4]]
"""
I believe that this calculation can be done more efficiently using numpy functions or using lambda functions. I'm not a programmer, and I'm new to Python. I would like to know if this could be done faster.