繁体   English   中英

如何复制此 R 向量 function 与 Python 中的 Rep

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

这是我的代码:

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

谢谢!

这应该类似于您在 R 中提供的内容:

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

在哪里:

  • df 是 Pandas dataframe 列名为“two”
  • Python 中的c()的等效结构是[]
  • 0是您要复制的值
  • 表达式(len(df.index) - 1) // 120)等价于rep(1:(nrow(df)-1)%/%120) 它使df中的行数减一,然后执行 integer 除法( %/% -> // )除以 120。
  • 该列表被放入 pd.Series 构造函数中,因为看起来您想将最终的 output 添加到dftwo列中。

如果您实际上是在寻找类似于rep()的 function ,请查看itertools中的repeat()方法。 这样的事情应该会给你一个类似的 output:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM