python - 根据 Pandas 中的当前值填充序列先前值

标签 python algorithm pandas dataframe

我有一个 pandas 数据框,如下所示:

ID   Value
1      2
2      6
3      3
4      5

我想要一个新的 dataframe

ID 值 1 0 1 1 1 2 2 0 2 1 2 2 2 3 2 4 2 5 2 6 3 1 3 2 3 3 3 4

如有任何建议,我们将不胜感激。

最佳答案

使用 reindexrepeatcumcount 来更新新值

df.reindex(df.index.repeat(df.Value+1)).assign(Value=lambda x : x.groupby('ID').cumcount())
Out[611]: 
   ID  Value
0   1      0
0   1      1
0   1      2
1   2      0
1   2      1
1   2      2
1   2      3
1   2      4
1   2      5
1   2      6
2   3      0
2   3      1
2   3      2
2   3      3
3   4      0
3   4      1
3   4      2
3   4      3
3   4      4
3   4      5

关于python - 根据 Pandas 中的当前值填充序列先前值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52598126/

相关文章:

python - 正则表达式仅从随机文本中搜索网站名称

java - 试图弄清楚经典的背包重现

algorithm - 在无向图中查找所有循环

php - 为自动增量图像的文件系统结构创建算法

python - 合并两个数据框并保留唯一列

python - 如何使用python来区分两个html文件

python - flask 管理员 : TextArea with monospace font

python - 一个变量多次出现如何获取请求值?

python - 如何在 Pandas 中定义用户定义的功能

Python Pandas 将初始列组融合为多个目标列