-1

I want to translate the following R code:

k =5 
Ret = as.data.frame(sapply(1:k, function(i) rnorm(k) ) )

deltas=NULL
for (i in 1:k) {
  y = Ret[,i]  
  mvalue = mean(y)
  minvec = NULL
  for (j in 1:length(y))
  {
    minvechelp = min(0,(y[j]-mvalue))
    minvec[j] = minvechelp
  }
  delta=sqrt(sum(minvec^2)/length(y))
  deltas = cbind(deltas,delta)
}
deltas

Which implements a collide mean of a data frame and then takes the length of the data frame to calculate a parameter delta which contains the min calculation but I think the df has been converted to vector.

In Python my effort is:

k= 5
A = pd.DataFrame(
      [np.random.randn(k) for i in range(k)]
   )
A.size
deltas = []
for i in range(0,k):
    y = Ret.iloc[:,i]  
    mvalue = np.mean(y)
    minvec = []
    for j in range(0,y.size):
        minvechelp = min(0,(y[j]-mvalue))
        minvec[j] = minvechelp
  
    delta=np.sqrt(sum(minvec**2)/y.size())
    deltas = np.hstack((deltas,delta))

deltas

but I receive an error

KeyError: 0

Where is my mistake and how can I fix it? Any help?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Homer Jay Simpson
  • 1,043
  • 6
  • 19
  • In which line did `KeyError: 0` orginated? – Daweo Feb 10 '22 at 11:19
  • @Daweo in the ```minvechelp = min(0,(y[j]-mvalue))``` – Homer Jay Simpson Feb 10 '22 at 11:20
  • For what it’s worth the R code could be improved drastically, and the resulting (loop-less) code would probably be much easier to translate into equivalent numpy code. – Konrad Rudolph Feb 10 '22 at 11:21
  • @KonradRudolph any help it is welcome – Homer Jay Simpson Feb 10 '22 at 11:21
  • Your code can be translated to 4 lines `mvalue <- colMeans(Ret); Res <- sweep(Ret, 2, mvalue); Res[Res >= 0] <- 0; delta <- sqrt(colSums(Res^2) / nrow(Ret))` in R. – Oliver Feb 10 '22 at 11:28
  • look at this site https://reddit.fun/33179/translate-python-for-loop-function-into-r – tomerar Feb 10 '22 at 11:45
  • 1
    @Oliver thanks for the simplification.In python reading [here](https://stackoverflow.com/questions/23117756/python-numpy-or-pandas-equivalent-of-the-r-function-sweep) it helps translating the sweep function from R to python but I cannot find the argument STATS.I think it has only the FUN argument equivalent in pandas – Homer Jay Simpson Feb 10 '22 at 12:24
  • Glad it turned out to be helpful – Oliver Feb 10 '22 at 12:39

1 Answers1

1

After Oliver's help in the comments I find out that the answer is :

mvalue = Ret.mean(axis=0);mvalue
Res = Ret - mvalue;Res
Res[Res>=0] = 0;Res
Res2 = Res**2
cs = Res2.sum(axis=0);cs
delta = np.sqrt(cs/Ret.shape[0]) 
delta
Homer Jay Simpson
  • 1,043
  • 6
  • 19