-1

I want to find the value of a new column dev for each row of a dataframe such that:

n=100
slope=0.8
inv=3
for i in range(0,n):
   dev += math.pow(src[i] - (slope * (n - i) + inv), 2)

Where src is a list of the previous n values of a column of the same dataframe.

Thus if my dataframe is:

Index A
0     1
1     2
2     4
3     5
4     2

And if the value of n is 3, the src for the row with index 3 will be:

[4, 2, 1]

What would be the most efficient way of going about this?

1 Answers1

0

Hello there MrOmnipotent. Do you mean something like this?

df['dev'] = 0 ##Create a column dev with dummy values

for idx in df.index: #interating on the indexes
    dev = 0
    for i in range(n+1): #interating on the n values
        if idx >= i:
            print(idx, '-', i, '=', idx-i) #idx - i is the values above the index
            dev += np.power(df.loc[idx-i]['A'] - (slope * (n - i) + inv), 2)
        elif idx < i:
            print('No rows above.') #There will be values idx-i < 0 of which are not valid indexes for our df
            pass        
    df['dev'][idx] = dev #Here I'm setting each dev value obtained after n+1 interations,i.e., n values above
  • While this is correct, I was wondering if there was a little less iterative process of doing this, perhaps by using an inbuilt functions. Another user suggested using rolling.apply() which may work. Thanks a lot anyway. – MrOmnipotent May 31 '21 at 15:14