1

I am trying to convert the following R script to Python. I am able to convert the individual lines of code to python. But could not find a way to apply for loop, as the following lines use the iterator variable i. date is datetime data type, week is string type. There are 3 data frames.length of new_levels is greater than df2$week unique(), levels Got stuck with this for loop for sometime.

df <- data.frame()
for(i in 1:NROW(df2)){
  temp <- subset(df1,df1$ID == df2$ID[i] & df1$week <= df2$week[i])
  temp_1 <- temp[order(factor(temp$week, levels = new_levels)),]
  temp <- tail(temp_1,6)
  
  temp$bookid <- df2$bookid[i]
  temp$plan <- df2$plan[i]
  temp$date <- df2$date[i]
  
  if(nrow(temp)>1){
    for(j in 1:NROW(temp)){
      temp$date[j] <- (temp$date[j] - (NROW(temp)-j)*24*3600*7)
    }
    temp1 <- temp[-nrow(temp),]
    df <- rbind(df,temp1)
  }


ruby
  • 71
  • 6
  • Never call `rbind` in a for-loop. It leads to excessive copying. Instead build a list of data frames and call `rbind` once. – Parfait Aug 11 '20 at 11:39
  • Also, please show Python attempt so we can help with your implementation. Like [R reproducible example](https://stackoverflow.com/q/5963269/1422451), please set up Pandas [reproducible example](https://stackoverflow.com/q/20109391/1422451). – Parfait Aug 11 '20 at 11:44

0 Answers0