Reputation: 6270
I have the following dataframe:
A.low A.up B C
0 1 3 1 D
1 1 2 2 E
2 2 4 1 E
how can I duplicate the rows in the range of the indexes A.low and A.up. The steps are integers. So my desired output would be:
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
Upvotes: 2
Views: 334
Reputation: 863166
Use Index.repeat
with DataFrame.loc
first, then create new column A
by GroupBy.cumcount
with A.low
and last create default 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
Upvotes: 3