0

Enumerate values rows by category

I have the following dataframe that I'm ordering by category and values:

d = {"cat":["a","b","a","c","c"],"val" :[1,2,3,1,4]  }
df = pd.DataFrame(d)
df = df.sort_values(["cat","val"])

enter image description here

Now from that dataframe I want to enumarate the occurrence of each category so the result is as follows:

df["cat_count"] = [1,2,1,1,2]

enter image description here

Is there a way to automate this?

cottontail
  • 10,268
  • 18
  • 50
  • 51
Luis Ramon Ramirez Rodriguez
  • 9,591
  • 27
  • 102
  • 181
  • 1
    Your output might be incorrect? Seems like your row order changed... Either way I'm guessing `df.groupby('cat').cumcount()+1` – ALollz Mar 13 '20 at 20:02

1 Answers1

1

You can use cumcount like this. Details here cumcount

df['count'] = df.groupby('cat').cumcount()+1
print (df)

Output

  cat  val  count
0   a    1      1
2   a    3      2
1   b    2      1
3   c    1      1
4   c    4      2
PraveenB
  • 1,270
  • 10
  • 11