It seems simple but I can’t seem to find an efficient way to solve this in Python 3: Is there is a loop I can use in my dataframe that takes every column after the current column (starting with the 1st column), and subtracts it from the current column, so that I can add that resulting column to a new dataframe?
This is what my data looks like:
on 3m 6m 9m 1y 18m 2y 3y 4y 5y 6y 7y 8y 9y 10y 15y 20y 25y
Dates
2010-03-09 0.5 0.52 0.58 0.90 1.19 2.01 2.70 3.66 4.37 4.87 5.32 5.54 5.77 5.80 5.89 6.04 6.19 NaN
2010-03-10 0.5 0.52 0.57 0.82 1.12 1.93 2.63 3.60 4.30 4.81 5.30 5.53 5.76 5.80 5.89 6.04 6.19 NaN
2010-03-11 0.5 0.52 0.57 0.80 1.10 1.93 2.63 3.58 4.30 4.81 5.30 5.53 5.76 5.80 5.89 6.04 6.19 NaN
2010-03-12 0.5 0.52 0.56 0.78 1.06 1.85 2.58 3.52 4.25 4.77 5.27 5.50 5.75 5.79 5.89 6.04 6.19 NaN
2010-03-15 0.5 0.52 0.56 0.76 1.05 1.84 2.56 3.52 4.25 4.75 5.25 5.48 5.73 5.76 5.86 6.01 6.16 NaN
This is what I want the resulting dataframe to look like:
Here is what I’ve done so far, but when running run_analysis
my “result” equation brings up an error.
storage = [] #container that will store the results of the subtracted columns
def subtract (a,b): #function to call to do the column-wise subtractions
return a-b
def run_analysis (frame, store):
for first_col_index in range(len(frame)): #finding the first column to use
temp=[] #temporary place to store the column-wise values from the analysis
for sec_col_index in range(len(frame)): #finding the second column to subtract from the first column
if (sec_col_index <= first_col_index): #if the column is below the current column or is equal to
#the current column, then skip to next column
continue
else:
result = [r for r in map(subtract, frame[sec_col_index], frame[first_col_index])]
#if column above our current column, the subtract values in the column and keep the result in temp
temp.append(result)
store.append(temp) #save the complete analysis in the store