How do I replicate this R vector function with Rep in Python

Question:

Here is my code:

  df$two <- c(0, rep(1:(nrow(df)-1)%/%120))

Thanks!

Asked By: user7446890

||

Answers:

This should be similar to what you’ve provided in R:

df["two"] = pd.Series([0] * ((len(df.index) - 1) // 120))

WHERE:

  • df is a Pandas dataframe with a column named "two"
  • An equivalent structure to c() in Python is []
  • 0 is the value you’re replicating
  • The expression (len(df.index) - 1) // 120) is equivalent to nrow(df)-1)%/%120. It gets the number of rows in df less one, then performs an integer division (%/% -> //) by 120.
  • The list is put into the pd.Series constructor because it looks like you want to add the final output to the two column in df.

If you’re actually instead looking for a function similar to rep(), look at the repeat() method from itertools. Something like this should get you a similar output:

df["two"] = pd.Series([0, *list(repeat(0, (len(df.index) - 1) // 120))])
Answered By: Ray
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.