learner
learner

Reputation: 2742

Creating a column of count in pandas dataframe

How to quickly add a column that counts the number of repetitions of [user, class] group.

For example;

user    class   val
1   2   23
1   2   23
1   3   29
1   3   29
1   4   11

The code groupby user and class and create a column that ranges from 1 (or 0) to the number of occurence of that group.

user    class   Mean    n_count
1   2   23  1
1   2   23  2
1   3   29  1
1   3   29  2
1   4   11  1

Upvotes: 0

Views: 43

Answers (1)

DSM
DSM

Reputation: 352959

You can use groupby and then cumcount:

>>> df["n_count"] = df.groupby(["user", "class"]).cumcount() + 1
>>> df
   user  class  val  n_count
0     1      2   23        1
1     1      2   23        2
2     1      3   29        1
3     1      3   29        2
4     1      4   11        1

Upvotes: 2

Related Questions