The following code creates a random dataframe with values -1, 0 or 1:
df = pd.DataFrame(np.random.randint(-1,2,size=(100, 1)), columns=['val'])
print(df['val'].value_counts())
Let's see what it contains:
-1 36
0 35
1 29
Name: val, dtype: int64
Then, I'm trying to create a new column called mysum
with a cumulative conditional sum which following the next rules:
- If val = 1 and mysum >= 0, then mysum = mysum + 1.
If val = 1 and mysum < 0, then mysum = mysum + 2.
If val = -1 and mysum <= 0, then mysum = mysum - 1.
If val = -1 and mysum > 0, then mysum = mysum - 2
If val = 0 and mysum < 0, then mysum = mysum + 1.
If val = 0 and mysum > 0, then mysum = mysum - 1.
If val = 0 and mysum = 0, then mysum = mysum.
So I'm afraid it is not as simple as:
df['mysum'] = df['val'].cumsum()
So I tried the following:
df['mysum'] = 0
df['mysum'] = np.where((df['val'] == 1) & (df['mysum'].cumsum() >= 0), (df['mysum'].cumsum() + 1), df['mysum'].cumsum())
df['mysum'] = np.where((df['val'] == 1) & (df['mysum'].cumsum() < 0), (df['mysum'].cumsum() + 2), df['mysum'].cumsum())
df['mysum'] = np.where((df['val'] == -1) & (df['mysum'].cumsum() <= 0), (df['mysum'].cumsum() - 1), df['mysum'].cumsum())
df['mysum'] = np.where((df['val'] == -1) & (df['mysum'].cumsum() > 0), (df['mysum'].cumsum() - 2), df['mysum'].cumsum())
df['mysum'] = np.where((df['val'] == 0) & (df['mysum'].cumsum() > 0), (df['mysum'].cumsum() - 1), df['mysum'].cumsum())
df['mysum'] = np.where((df['val'] == 0) & (df['mysum'].cumsum() < 0), (df['mysum'].cumsum() + 1), df['mysum'].cumsum())
print(df['mysum'].value_counts())
print(df)
But the column mysum
is not accumulating!
Here is a fiddle where you can try: https://repl.it/FaXZ/8