To start, I have a DataFrame that looks like the following:
df = pd.DataFrame({'a': [25, 22, -2, 16, 10], 'b': [-5, 18, -2, 25, 48], 'c': [34, -12, 7, 8, 22],
'd': [10, 8, -2, -4, 12]})
Goal: Eliminate all zeroes using a specific script or function that preserves the effect of the negative value within each column.
I am trying to develop a method to look through a data frame, find the negative values and take the absolute value of the negative value and add one. In essence, this will replace each negative value in the DataFrame with positive value of one.
Next, I want to subtract the value I calculated after taking the absolute value of the negative number (plus one) and subtract it from the next row value (within that same column).
In addition: In cases where the value following a negative value is also negative, I want to do the same operation for both negative values, but I want to subtract the sum of the absolute value plus one, for each negative number, and subtract it from the next positive row. If the row value following the corrected negative becomes less than 1 after I want to subtract off from the row after that, until the negative value is gone and no rows following them are less than 1.
The expected output will hopefully help grasp what I intend to do:
expected_output = pd.DataFrame({'a': [25, 22, 1, 13, 10], 'b': [1, 12, 1, 22, 48],
'c': [34, 1, 1, 1, 22],'d': [10, 8, 1, 1, 4]})
I can replace the negative value with the absolute value of the negative value, plus one, using:
df[df < 0] = abs(df[df < 0] + 1)
I also know I can find the location of the negative value using:
neg_loc = df.loc[df['a'] < 0].index
Now I find the value after the negative value using:
row_after_neg = df['a'].iloc[neg_loc + 1]
Lastly, I can add the absolute value of the negative value plus one to the row after the negative value with:
total = row_after_neg.add(abs(neg_loc + 1))
So, my question is how do I stitch this together so that it goes through the entire DataFrame and does what I specified.
Thank you in advance for the advice/help!