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!
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))])
Here is my code:
df$two <- c(0, rep(1:(nrow(df)-1)%/%120))
Thanks!
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 tonrow(df)-1)%/%120
. It gets the number of rows indf
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 indf
.
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))])