I want to expand my data frame based on numeric values in two columns (index_start
and index_end
). My df looks like this:
item index_start index_end
A 1 3
B 4 7
I want this to expand to create rows for A from 1 to 3 and rows for B from 4 to 7 like so.
item index_start index_end index
A 1 3 1
A 1 3 2
A 1 3 3
B 4 7 4
B 4 7 5
B 4 7 6
B 4 7 7
Unsure how to implement this in Python/pandas.
You could use .explode()
df['index'] = df.apply(lambda row: list(range(row['index_start'], row['index_end']+1)), axis=1)
df.explode('index')
item index_start index_end index
0 A 1 3 1
0 A 1 3 2
0 A 1 3 3
1 B 4 7 4
1 B 4 7 5
1 B 4 7 6
1 B 4 7 7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With