python - 数据框的值范围中的重复行
问题描述
我有以下数据框:
A.low A.up B C
0 1 3 1 D
1 1 2 2 E
2 2 4 1 E
如何复制索引 A.low 和 A.up 范围内的行。步数是整数。所以我想要的输出是:
A.low A.up B C A
0 1 3 1 D 1
1 1 3 1 D 2
2 1 3 1 D 3
3 1 2 2 E 1
4 1 2 2 E 2
5 2 4 1 E 2
6 2 4 1 E 3
7 2 4 1 E 4
解决方案
首先使用Index.repeat
with ,然后使用withDataFrame.loc
创建新列A
,最后创建默认值:GroupBy.cumcount
A.low
RangeIndex
df = df.loc[df.index.repeat(df['A.up'] - df['A.low'] + 1)]
df['A'] = df.groupby(level=0).cumcount() + df['A.low']
df = df.reset_index(drop=True)
print (df)
A.low A.up B C A
0 1 3 1 D 1
1 1 3 1 D 2
2 1 3 1 D 3
3 1 2 2 E 1
4 1 2 2 E 2
5 2 4 1 E 2
6 2 4 1 E 3
7 2 4 1 E 4
推荐阅读
- javascript - 基于 vue-route-link active 的动态颜色
- azure - 在 Azure 托管的多容器 Web 应用程序中,无法连接到 unix:///var/run/docker.sock 上的 Docker 守护程序
- python - 上传到 GitHub 的 Jupyter notebook 不显示folium map
- assembly - 大会 AT&T:movq %rdi, %rdx?
- java - 无法解决关闭 preparesStatement 的 SonarQube 错误
- ios - 无效的 `Podfile` 文件:无法加载此类文件 -- path/to/.ios/Flutter/podhelper.rb
- powerbi - Power Bi 排序日期表
- html - 用 svg 中的透明路径重叠彩色矩形/在与路径的交叉点上破坏矩形填充颜色
- go - 如何解压单个文件?
- regex - 需要删除删除正则表达式中的模式/字符串(记事本++)