Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (45.3k points)

For instance, I have thousands of row with one of its is column 'cow_ID' where each cow ID have several rows. I want to replace those ID with the number starting from 1 just to make it easier to remember.

df['cow_id'].unique().tolist()

resulting in:

 5603,

 5606,

 5619,

 4330,

 5587,

 4967,

 5554,

 4879,

 4151,

 5501,

 4723,

 4908,

 3963,

 4023,

 4573,

 3986,

 5668,

 4882,

 5645,

 5548

How do I change each unique ID into a new number such as:

5603 -> 1

5606 -> 2

1 Answer

0 votes
by (16.8k points)

Try this:

df.groupby('cow_id').ngroup()+1

Or try to factorize is by pd.factorize:

pd.factorize(df['cow_id'])[0]+1

Refer to this official doc on pd.factorize

Browse Categories

...