I have a dataset that has several rows and columns, however within the column labeled, 'active', I wish to remove the aggregation and separate this into its own unique count. I also wish to add a column that gives this count a unique id.
Data
Pair gen box date active
sox black bl 2021 3
sox red re 2021 2
Desired
Pair gen box date active count
sox black bl 2021 1 b101
sox black bl 2021 1 bl02
sox black bl 2021 1 bl02
sox red re 2021 1 re01
sox red re 2021 1 re02
The 'active' column now has 3 and 2 distinct rows respectively, along with a distinct count ID (based on the 'box' column) instead of an aggregation.
Doing
A SO assisted with a similar dilemma, and I am taking this approach:
# Melt Table Into New Form
df = df.melt(col_level=0, value_name='count', var_name='bl')
# Repeat Based on Count
df = df.reindex(df.index.repeat(df['count']))
# Set Count To 1
df['count'] = 1
# Add Suffix to Each ID
df['ID'] = df['ID'] + (
(df.groupby('ID').cumcount() + 1)
.astype(str)
.str.zfill(2)
)
This works, however, I am not able to retain the other columns as well as set individual var names such as:
bl01
bl02
re01
re02
Any suggestion or advice is appreciated