Home > Mobile >  Re-enumerate column B contents based on Column A
Re-enumerate column B contents based on Column A

Time:08-17

I have the following dataframe:

df = pd.DataFrame({'Category':[101,101,101,103,103,103,103],
                   'Sub-Category':[0,3,4,0,2,4,5]})

df
  Category Sub-Category
0   101      0
1   101      3
2   101      4
3   103      0
4   103      2
5   103      4
6   103      5

But I want to re-enumerate items in sub-category based on each corresponding Category. So that the final result is:

  Category Sub-Category
0   101      1
1   101      2
2   101      3
3   103      1
4   103      2
5   103      3
6   103      4

CodePudding user response:

You can use .cumcount with a .groupby

df["Sub-Category"] = df.groupby(
    "Category", as_index=False
)["Sub-Category"].cumcount()

# start at 1 instead of 0
df["Sub-Category"]  = 1

print(df)

   Category  Sub-Category
0       101             1
1       101             2
2       101             3
3       103             1
4       103             2
5       103             3
6       103             4

  • Related