首页 > 解决方案 > 数据框的值范围中的重复行

问题描述

我有以下数据框:

   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

标签: pythonpandas

解决方案


首先使用Index.repeatwith ,然后使用withDataFrame.loc创建新列A,最后创建默认值:GroupBy.cumcountA.lowRangeIndex

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

推荐阅读